2017-02-01 7 views
1

私はusersテーブルと3つのテーブルにユーザーの収入があります。
私がしようとしているのは、これらの3つのテーブルに基づいて最も収益の高い上位10人のユーザーを選択することです。
私は昨日からこの要求に苦労しており、私はそれを動作させることができません。
合計3つの収益テーブルを合計します。3つのテーブルから合計収益を得る

お願いします。

SELECT 
    users.first_name, 
    users.last_name, 
    (select SUM(`value`) from `earnings1` where users.id = earnings1.user) as earnings1, 
    (select SUM(`value`) from `earnings2` where users.id = earnings2.user) as earnings2, 
    (select SUM(`value`) from `earnings3` where users.id = earnings3.user) as earnings3, 
    (earnings1 + earnings2 + earnings3) as total  
FROM users 
GROUP BY users.id 
ORDER BY total DESC  
LIMIT 10 

私は今取得していますエラーは次のとおりです。

'フィールドリスト' 内の不明な列 'earnings1'

+0

エラーは何ですか? – MontyPython

+0

今、 '不明な列 'フィールドリスト'の 'earnings1' ' – divHelper11

+0

そして、' earnings1'テーブルの列は何ですか? –

答えて

1

これはあなたのために働く必要があります。

select first_name, last_name, 
(earnings1 + earnings2 + earnings3) total from 
(select users.id, users.first_name, users.last_name, 
(select sum(`value`) from `earnings1` where users.id = earnings1.user) as earnings1, 
(select sum(`value`) from `earnings2` where users.id = earnings2.user) as earnings2, 
(select sum(`value`) from `earnings3` where users.id = earnings3.user) as earnings3 
from users group by 1,2,3) t 
order by 3 desc limit 10 

は、内部から結果セットを与える名前です。クエリ。これは、共通のテーブル式に似ていますが、正確ではありません。 MySQLでは、この結果セットに名前を付ける必要があります。

1,2,3あなたはどちらかのユーザーは、1,2,3またはあなたのグループ化列として列名users.id、users.first_name、users.last_nameを使用することができます。 1,2,3は、select文の1番目、2番目、3番目の列を意味します。

+0

ありがとうございました:) '1,2,3'がどこから来たのか教えてください。そして、このtは、AS tのように同じですか? – divHelper11

+0

@ divHelper11 - 編集を行ったので、今すぐ確認してください。 – MontyPython

関連する問題