关于一个 sql 语句的疑问

2020-06-08 17:04:10 +08:00
 18870715400

表结构

+-------+---------------+------+-----+---------+-------+
| 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 语句来解决这个错误呢

2036 次点击
所在节点    Python
8 条回复
jiorix
2020-06-08 17:37:02 +08:00
最外层的 select 没有写 group by ?
breadenglish
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
dog82
2020-06-08 17:53:09 +08:00
最外层用了聚合函数,但是没分组……
18870715400
2020-06-08 18:03:07 +08:00
@breadenglish 受教了 我写错了 谢谢
18870715400
2020-06-08 18:05:20 +08:00
@dog82 使用了聚合函数不一定需要 group by 吧,不然我原先的好多 sql 语句都有问题
dog82
2020-06-08 18:07:24 +08:00
@18870715400 mysql 好像可以不 group by,这样写不符合 sql 规范
srlp
2020-06-09 01:26:42 +08:00
使用聚合函数,除非全部字段都是聚合了,不然还是要加上 group by 最为规范。这保证了满足 sql 规范,日后迁移到其他 sql 引擎也好迁移。

mysql 只是某些情况下可以接受不规范的 sql 而已,正如你贴出 this is incompatible with sql_mode=only_full_group_by 说的就是这一回事。
srlp
2020-06-09 01:27:31 +08:00
@dog82 #6 同意层主说的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/679771

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX