简体   繁体   English

mysql 加入子查询问题

[英]mysql joins with subqueries issue

I have issue combining sql join with group & subquery to select max value.我在将 sql join 与 group & subquery 结合以选择最大值时遇到问题。

table1表格1

user_id user_name
1   x
2   t
3   y
4   i
5   o

table2表2

user_id game_id
1   soccer
2   soccer
2   pool
2   basketball
5   swimming

table3表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

When running this query, which is grouping all game_ids by user_ids I've a success:运行此查询时,它按 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

But when trying to combine subquery to return the latest fans' number:但是当尝试组合子查询以返回最新的粉丝数时:

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

I'm facing issue with the group function:我面临组功能的问题:

#1111 - Invalid use of group function #1111 - 无效使用组功能

Edit:编辑:

Fixed the issue #1111 by changing WHERE to HAVING but my query is still no good as MYSQL report the following:通过将 WHERE 更改为 HAVING 修复了问题 #1111,但我的查询仍然不好,因为 MYSQL 报告如下:

Unknown column 'table3.fans' in 'field list' “字段列表”中的未知列“table3.fans”

If you use aggregation function you must declare in group by clause all the columns not involved in aggregation function.如果使用聚合函数,则必须在 group by 子句中声明聚合函数中不涉及的所有列。

You are using an aggregation function MAX(update_time) in where clause and this raise the error invalid use of group function .您在 where 子句中使用聚合函数MAX(update_time)这会引发错误invalid use of group function

the use of an aggregated function in where is not allowed eventually you could filter this result using having clause ..最终不允许在 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 

in you case you are also referring to a table3 that is in subquery and is not visibile outside .. so you should refer to this columns using the alias that you have used for the table result of the subquery (fans)在您的情况下,您还指的是在子查询中并且在外部不可见的 table3,因此您应该使用用于子查询的表结果的别名来引用此列(粉丝)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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