我正在使用外部数据库,并且有 3 个重要列:user_id、total_score、score_order。
我想获取每个用户的total_score。
所有的分数都会被记录下来,所以我只需要最后一个。为此,我需要使用 score_order 列。
这就是我想要做的(使用嵌套查询,因为我需要组合 ORDER BY 和 GROUP BY):
SELECT * FROM (
SELECT * FROM `table` ORDER BY score_order DESC
) AS tmp_table GROUP BY user_id
但我收到错误:
'#1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'tmp_table.ranking_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by Can someone explain what I am doing wrong?'
最佳答案
在默认的 GROUP BY 模式下,您只能选择 group by 子句中的列或列上的聚合。
例如,这可能有效:
SELECT user_id, MAX(total_score), MAX(score_order) as score_order_max
FROM `table` GROUP BY user_id ORDER BY score_order_max DESC;
它与user_id
一起使用,因为它位于分组依据中,并且其他两列是聚合。
我认为你不需要双重选择,因为 MySql 不是 Oracle。
关于MySQL - ORDER BY 和 GROUP BY 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57254221/