mysql - MySQL - ORDER BY and GROUP BY together
问题描述
I am using an external DB and I have 3 important columns: user_id, total_score, score_order.
I would like to get the total_score of each user.
All the scores are always recorded, so I only need the last one. For this I need to use the score_order column.
This is what I am trying to do (using nested queries because I need to combine ORDER BY and GROUP BY):
SELECT * FROM (
SELECT * FROM `table` ORDER BY score_order DESC
) AS tmp_table GROUP BY user_id
But I get the error:
'#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
因为它在 group by 中,而另外两列是聚合。
我认为您不需要双重选择,因为 MySql 不是 oracle。
推荐阅读
- php - 当特定产品在 Woocommerce 的购物车中时,将加拿大从国家/地区列表中删除
- r - 当我尝试运行 for 循环时,为什么 R 会删除我文件中的所有信息?
- javascript - 停止输入重新渲染 onChange
- css - CSS中的自动幻灯片过渡循环
- ssl - 如果是自签名证书,浏览器是否不验证数字签名
- c# - 如何将 C++ 控制台参数发送到 C# DLL
- r - 基于多个范围合并
- reverse-engineering - 缓冲区溢出 - 没有足够的空间用于 shellcode
- android - 我无法减小我的 React-Native Android 应用程序的大小
- ibm-cloud - 如何找到当前版本的 IBM Hyperledger Fabric?