I have issue combining sql join with group & subquery to select max value.
table1
user_id user_name
1 x
2 t
3 y
4 i
5 o
table2
user_id game_id
1 soccer
2 soccer
2 pool
2 basketball
5 swimming
table3
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:
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
Edit:
Fixed the issue #1111 by changing WHERE to HAVING but my query is still no good as MYSQL report the following:
Unknown column 'table3.fans' in 'field list'
If you use aggregation function you must declare in group by clause all the columns not involved in aggregation function.
You are using an aggregation function MAX(update_time)
in where clause and this raise the error 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 ..
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.