需求找出最近练习过的句子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 byselect * from practicesorder by created_at descgroup by pth_sentence_idlimit 5 出错了
为啥呢?order by 需要在group by 的后面执行!并且要用where语句的话需要放在group by之前! 调整下顺序: select * from practicesgroup by pth_sentence_idorder by created_at desclimit 5 还是出错,请原谅我好久没写SQL了:
为啥呢?因为id没有写在group by 语句中, group by 是要与聚合函数结合起来使用的。 好,我不写id了,改成这样呢? select pth_sentence_id from practicesgroup by pth_sentence_idorder by created_at desclimit 5 继续出错。
这回是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中加入maxorder by 中的日期排序添加上max聚合函数,且:group by里面只有一个分组条件,pth_sentence_id,这样就得到了包含唯一pth_sentence_id的practices纪录,并且还是最近生成(按照created_at倒序排列)的5条practice记录。 加入where语句最近的几次练习都是用户6的,所以与上面结果一致。 |
|
来自: Fengsq501u81r4 > 《计算机》