繁体   English   中英

mysql 加入子查询问题

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM