Mysql
如何對子查詢中的值求和
我需要從多個表中收集一些值並將這些值作為一列匯總到結果表中。
我的查詢如下所示:
SELECT u.ID as id, ( SELECT `meta_value` as user_name FROM `wxe4_usermeta` WHERE `umeta_id` = u.ID AND `meta_key` = 'nickname' ) as user_name, ( SELECT SUM(rounds) FROM wxe4_170 WHERE user = u.ID ) as a170_score, ( select IF (count(*) > 0, count(*)*66, 0) FROM wxe4_aroundtheworld WHERE user = u.ID ) as atw_score, ( select IF (count(*) > 0, count(*)*100, 0) FROM wxe4_X100 WHERE user = u.ID ) as x100_score, SUM(a170_score + atw_score + x100_score) as darts_total_thrown FROM darts.wxe4_users as u
總和引發“錯誤程式碼:1054。‘欄位列表’中的未知列’a170_score’”錯誤。
我得到的沒有總和:
| id | user_name | a170_score | atw_score | x100_score | -------------------------------------------------------- | 1 | someUser | 449 | 3102 | 200 |
我對總和的期望:
| id | user_name | a170_score | atw_score | x100_score | darts_total_thrown | ---------------------------------------------------------------------------- | 1 | someUser | 449 | 3102 | 200 | 3751 |
為什麼我不能訪問這些值以及如何解決這個問題?
您不能以這種方式使用新列。使用子查詢使用數據進行計算
SELECT wxe4_usern.*,(wxe4_usern.a170_score + wxe4_usern.atw_score + wxe4_usern.x100_score) as darts_total_thrown FROM (SELECT u.ID as id, ( SELECT `meta_value` as user_name FROM `wxe4_usermeta` WHERE `umeta_id` = u.ID AND `meta_key` = 'nickname' ) as user_name, ( SELECT SUM(rounds) FROM wxe4_170 WHERE user = u.ID ) as a170_score, ( select IF (count(*) > 0, count(*)*66, 0) FROM wxe4_aroundtheworld WHERE user = u.ID ) as atw_score, ( select IF (count(*) > 0, count(*)*100, 0) FROM wxe4_X100 WHERE user = u.ID ) as x100_score FROM darts.wxe4_users as u) wxe4_usern