打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
SQL|where, group by, order by去重实例之如何正确使用group by

需求

找出最近练习过的句子id,不能重复(练习保存在practice表中,句子保存在pth_sentences表中,一个pth_sentence纪录有多条practices纪录)。现在的情况是如果一个句子练习多次,会得到重复的pth_sentence_id,这样前端在列出来的时候呢,句子是重复的,我只想让句子显示一次,既pth_sentence_id只出现一次。

Practices的表结构是这样的:

CREATE TABLE `practices` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` int(11) DEFAULT NULL, `pth_sentence_id` int(11) DEFAULT NULL, `local_sound` varchar(255) DEFAULT NULL, `comment` varchar(255) DEFAULT NULL, `created_at` datetime(6) NOT NULL, `updated_at` datetime(6) NOT NULL, `soundfile` json DEFAULT NULL, `del` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=215 DEFAULT CHARSET=utf8mb4;

一步步写出满足需求的SQL语句好喽,以前老师就是这么教的。

最近句子练习纪录5条

so easy. 问题就是句子id有重复,需要去重。

加入group by

select * from practicesorder by created_at descgroup by pth_sentence_idlimit 5

出错了

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group by pth_sentence_id limit 10' at line 3

为啥呢?order by 需要在group by 的后面执行!并且要用where语句的话需要放在group by之前!

调整下顺序:

select * from practicesgroup by pth_sentence_idorder by created_at desclimit 5

还是出错,请原谅我好久没写SQL了:

1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'beginner.practices.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

为啥呢?因为id没有写在group by 语句中, group by 是要与聚合函数结合起来使用的。

好,我不写id了,改成这样呢?

select pth_sentence_id from practicesgroup by pth_sentence_idorder by created_at desclimit 5

继续出错。

1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'beginner.practices.created_at' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

这回是group by中的created_at呢,说没有在group_by语句中。好,加进去。

倒是没错了,但结果不是我想要的,因为这连个id都没有,而且数据有重复。

加入id

怎么把id加进去呢?需要使用聚合函数,比如max, min这样的,看你实际的需要。

我这个例子里面加上max相当于说我要找出一个句子的练习中practice.id最大的那一个practice纪录!

但如果在group by里面添加created_at之后并没有去重,查了下,这种group by会同时在pth_sentence_id和created_at两个字段进行分组,不是按照pth_sentence_id这一个条件进行分组,这就需要最后神奇的下一步:

order by中加入max

order by 中的日期排序添加上max聚合函数,且:group by里面只有一个分组条件,pth_sentence_id,这样就得到了包含唯一pth_sentence_id的practices纪录,并且还是最近生成(按照created_at倒序排列)的5条practice记录。

加入where语句

最近的几次练习都是用户6的,所以与上面结果一致。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【第16天】SQL进阶-查询优化一定要学EXPALIN (SQL 小虚竹)
覆盖索引(covering index)一次神奇的MySQL优化
SQL基础入门:第13课:汇总统计及GROUP BY(1)
一条SQL语句查询出成绩名次排名
hive大数据倾斜总结
Oracle的rollup、cube、grouping sets函数
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服