2010-11-18 2 views
1

私自身の啓発のために、このSQL機能を一時テーブルを使用せずに1つのステートメントに書き込もうとしています。私の人生にとって、私はMySQLの "エラー1248(42000)を取得せずにクエリを取得することはできません:すべての派生テーブルは、独自のエイリアスを持っている必要があります。壊れたとはいえここで派生テーブルを使用してこのSQLを単一ステートメントとして表現する方法を説明してください

は、私が欲しいものに、似て何か:助けを

CREATE TEMPORARY TABLE weightsum (share INT, sum INT); 

INSERT INTO weightsum (share, sum) 
SELECT split.share, SUM(weight) AS sum 
FROM split 
GROUP BY split.share; 

CREATE TEMPORARY TABLE summary (share INT, weight INT, creditor INT, debtor INT, amount DECIMAL(10,2)); 

INSERT INTO summary (share, weight, creditor, debtor, amount) 
SELECT split.share, split.weight, split.creditor, split.debtor, share.amount 
FROM (split LEFT JOIN share ON split.share = share.id) 
WHERE debtor = 6 OR creditor = 6; 

SELECT summary.share, summary.weight, weightsum.sum, summary.creditor, summary.debtor, summary.amount, ((summary.amount/weightsum.sum) * summary.weight) AS split_amount 
FROM summary LEFT JOIN weightsum 
ON summary.share = weightsum.share; 

ありがとう:

SELECT split.share, split.weight, split.creditor, split.debtor, share.amount, wsum.sum 
FROM (
    SELECT split.share, split.weight, split.creditor, split.debtor, share.amount 
    FROM (split LEFT JOIN share ON split.share = share.id) 
    WHERE debtor = 6 OR creditor = 6) 
    LEFT JOIN (
     SELECT split.share, SUM(weight) AS sum 
     FROM split 
     GROUP BY split.share 
    ) wsum 
    ON split.share = wsum.share; 

は、ここで私は一時テーブルを使用して表現しようとしている何の作業バージョンです。

答えて

0

これを試してみてください:より正確に書かれた

SELECT split.share, split.weight, split.creditor, split.debtor, share.amount, wsum.sum 
FROM (
    SELECT split.share, split.weight, split.creditor, split.debtor, share.amount 
    FROM split 
    LEFT JOIN share 
    ON split.share = share.id 
    WHERE debtor = 6 OR creditor = 6 
) As split 
LEFT JOIN (
    SELECT split.share, SUM(weight) AS sum 
    FROM split 
    GROUP BY split.share 
) wsum 
ON split.share = wsum.share; 

または:

SELECT split.share, split.weight, split.creditor, split.debtor, share.amount, wsum.sum 
FROM split 
LEFT JOIN share 
ON split.share = share.id 
LEFT JOIN (
    SELECT split.share, SUM(weight) AS sum 
    FROM split 
    GROUP BY split.share 
) wsum 
ON split.share = wsum.share 
WHERE split.debtor = 6 OR split.reditor = 6; 
関連する問題