[英]mysql joins with subqueries issue
我在將 sql join 與 group & subquery 結合以選擇最大值時遇到問題。
表格1
user_id user_name
1 x
2 t
3 y
4 i
5 o
表2
user_id game_id
1 soccer
2 soccer
2 pool
2 basketball
5 swimming
表3
user_id fans date
1 54805 2018-10-05
2 10005 2018-10-05
2 10023 2018-10-03
3 175 2018-10-05
4 1542 2018-10-05
運行此查詢時,它按 user_ids 對所有 game_ids 進行分組,我成功了:
SELECT table1.user_id, table1.user_name, group_concat(table2.game_id) as games
FROM (table1
LEFT JOIN table2 on table2.user_id = table1.user_id)
group by table1.user_id
但是當嘗試組合子查詢以返回最新的粉絲數時:
SELECT table1.user_id, table1.user_name, group_concat(table2.game_id) as games, table3.fans
FROM ((table1
LEFT JOIN table2 on table2.user_id = table1.user_id)
INNER JOIN (SELECT * FROM table3 WHERE MAX(update_time) ORDER BY update_time LIMIT 1) AS fans ON table1.user_id = table3.user_id)
group by table1.user_id
我面臨組功能的問題:
#1111 - 無效使用組功能
編輯:
通過將 WHERE 更改為 HAVING 修復了問題 #1111,但我的查詢仍然不好,因為 MYSQL 報告如下:
“字段列表”中的未知列“table3.fans”
如果使用聚合函數,則必須在 group by 子句中聲明聚合函數中不涉及的所有列。
您在 where 子句中使用聚合函數MAX(update_time)
這會引發錯誤invalid use of group function
。
最終不允許在 where 中使用聚合函數,您可以使用 have 子句過濾此結果..
SELECT table1.user_id
, table1.user_name
, group_concat(table2.game_id) as games
, fans.my_res
FROM table1
INNER JOIN (
SELECT user_id, MAX(update_time) my_res FROM table3
group by user_id
ORDER BY my_res DESC LIMIT 1
) AS fans ON table1.user_id = fans.user_id
LEFT JOIN table2 on table2.user_id = table1.user_id
group by table1.user_id, table1.user_name, fans.my_res
在您的情況下,您還指的是在子查詢中並且在外部不可見的 table3,因此您應該使用用於子查詢的表結果的別名來引用此列(粉絲)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.