业务场景:
取一张表里面最新的一条数据,以最新的一条数据为基准进行相关业务操作。
创建我们需要的测试表
create table my_test
(
id int auto_increment
primary key,
name varchar(255) null,
create_date date null
);
INSERT INTO my_test (id, name, create_date) VALUES (1, '赵琪', '2022-03-18');
INSERT INTO my_test (id, name, create_date) VALUES (6, '王妤', '2022-03-18');
INSERT INTO my_test (id, name, create_date) VALUES (9, '张彤', '2022-03-18');
INSERT INTO my_test (id, name, create_date) VALUES (2, '赵琪', '2022-03-16');
INSERT INTO my_test (id, name, create_date) VALUES (4, '王妤', '2022-03-16');
INSERT INTO my_test (id, name, create_date) VALUES (7, '张彤', '2022-03-16');
INSERT INTO my_test (id, name, create_date) VALUES (5, '王妤', '2022-03-15');
INSERT INTO my_test (id, name, create_date) VALUES (11, '张彤', '2022-03-15');
INSERT INTO my_test (id, name, create_date) VALUES (32, '赵琪', '2022-03-15');
数据准备好,我们来查询一下
-
不建议使用的方案
从网上找的其他解决方案,说的是先按照时间排序,然后再分组,通过 max 函数取出自己想要的字段值,经过验证,此方案取的个别字段,与最新的记录数据匹配不上,如下:
select max(id), name, max(create_date)
from (
select *
from my_test
order by create_date desc) t
group by name;
执行结果:
仔细看,这个结果里面的 ID 字段值,通过 max 取出来的,和上面我们的原数据 ID 值,已经不能匹配了,所以,不建议使用这种方案!!
- 建议使用的解决方案
为了保证我们最终取到的数据,是完全匹配的,我们采用 not exist 的方式来处理,这样,取出来的数据,就是最完美的了。如下:
select *
from my_test mt
where not exists(
select 1 from my_test t
where mt.name = t.name
and mt.create_date < t.create_date
);
我们来看一下结果:
发现,最终取到的数据刚好和我们预期的一样,简直是完美!
希望这篇短短的文章,能帮到需要的小伙伴!有什么问题,也可以一起交流探讨~