3

Mysql distinct 和 order by 排序混淆的替代方案

 1 year ago
source link: https://hxd.life/2022/12/30/MySQL-distinct-%E5%92%8C-order-by-%E6%8E%92%E5%BA%8F%E6%B7%B7%E6%B7%86%E7%9A%84%E6%9B%BF%E4%BB%A3%E6%96%B9%E6%A1%88/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Mysql distinct 和 order by 排序混淆的替代方案

author: alpha 的博客 date: 2022-12-30

场景是:从一堆学习记录中,去重并获取最近学习的几条课程ID,随手就能想到这样的一条SQL语句:

select distinct a from table order by updated_at desc limit 5

如果列为 a 的数据有很多条,就会发现最终取到的那条数据可能不是 updated_at 最近的那条数据,因为 distinct 有一次默认的排序,然后生成一个临时表, 然后 order by 无法从最开始的原始数据中进行排序,仅排序中间表,无法得出正确结果。改成 distinct a, updated_at 的话, 实际上又失去了 distinct 的意义了。

方案一: 使用子查询方式,将结果先排序,当做一个表,然后去重保留最新的一条数据

select distinct a from (select a from table order by updated_at desc) t limit 5

方案二: 借助 max 和 group by 特性直接取最大值,取值

select a, max(updated_at) from table group by a order by updated_at desc limit 5


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK