表结构
+-------+---------------+------+-----+---------+-------+
| Field | Type          | Null | Key | Default | Extra |
+-------+---------------+------+-----+---------+-------+
| SId   | varchar(10)   | YES  |     | NULL    |       |
| CId   | varchar(10)   | YES  |     | NULL    |       |
| score | decimal(18,1) | YES  |     | NULL    |       |
+-------+---------------+------+-----+---------+-------+
按照学生 SId 统计不同学生的总分数并且显示排名
我的 sql 语句
select t1.SId, t1.total_score, count(t2.total_score)+1 rank from 
(select score.SId, sum(score) total_score from score group by SId) t1 
left join 
(select score.SId, sum(score) total_score from score group by SId) t2
on t1.SId = t2.SId and t2.total_score > t1.total_score
order by rank asc
报错提示:
In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 't1.SId'; this is incompatible with sql_mode=only_full_group_by
mysql 版本:5.7.30
网上说更改相关的配置就可以, 但是除了更改相关 mysql 配置还有什么办法更改 sql 语句来解决这个错误呢
我的 sql 语句
select t1.SId, t1.total_score, count(t2.total_score)+1 rank from 
(select score.SId, sum(score) total_score from score group by SId) t1 
left join 
(select score.SId, sum(score) total_score from score group by SId) t2
on t1.SId = t2.SId and t2.total_score > t1.total_score
order by rank asc
报错提示:
In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 't1.SId'; this is incompatible with sql_mode=only_full_group_by
mysql 版本:5.7.30
网上说更改相关的配置就可以, 但是除了更改相关 mysql 配置还有什么办法更改 sql 语句来解决这个错误呢
|  |      1jiorix      2020-06-08 17:37:02 +08:00 最外层的 select 没有写 group by ? | 
|  |      2breadenglish      2020-06-08 17:53:02 +08:00 >> on t1.SId = t2.SId and t2.total_score > t1.total_score 这个逻辑也有点问题吧,两个子查询都用 SId 取的总分,再用 SId 相等取出来的不就还是自己么。 应该是 on t1.SId != t2.SId and t2.total_score > t1.total_score 吧 | 
|  |      3dog82      2020-06-08 17:53:09 +08:00 最外层用了聚合函数,但是没分组…… | 
|  |      418870715400 OP @breadenglish 受教了  我写错了  谢谢 | 
|  |      518870715400 OP @dog82 使用了聚合函数不一定需要 group by 吧,不然我原先的好多 sql 语句都有问题 | 
|  |      6dog82      2020-06-08 18:07:24 +08:00 @18870715400 mysql 好像可以不 group by,这样写不符合 sql 规范 | 
|      7srlp      2020-06-09 01:26:42 +08:00 使用聚合函数,除非全部字段都是聚合了,不然还是要加上 group by 最为规范。这保证了满足 sql 规范,日后迁移到其他 sql 引擎也好迁移。 mysql 只是某些情况下可以接受不规范的 sql 而已,正如你贴出 this is incompatible with sql_mode=only_full_group_by 说的就是这一回事。 |