首页 > 解决方案 > mysql加入子查询问题

问题描述

我在将 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

我遇到了 group 功能的问题:

#1111 - 组功能的使用无效

编辑:

通过将 WHERE 更改为 HAVING 修复了问题 #1111,但我的查询仍然不好,因为 MYSQL 报告以下内容:

“字段列表”中的未知列“table3.fans”

标签: mysqljoinsubquery

解决方案


如果使用聚合函数,则必须在 group by 子句中声明聚合函数未涉及的所有列。

MAX(update_time)您在 where 子句 中使用聚合函数,这会引发错误invalid use of group function

最终不允许在 where 中使用聚合函数,您可以使用 having 子句过滤此结果..

 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 并且在外部不可见 .. 所以您应该使用您用于子查询的表结果的别名来引用这些列(粉丝)


推荐阅读