我们简单还原一下,这里使用一个表模拟下
表的字段如下
表的内容如下,我们的需求就是取出相同name的数据中时间最新的一条。
不知道大家首先会想到什么,我第一想到的是使用group,当时认为分组不就是group吗,害,easy
然后我就开始了尝试,结果。。。。。
就在我想要放弃的时候,我突然脑子清醒了,开始仔细思考这个需求,不就是把每个名字和最新的时间拿出来,然后再根据名字和最新时间直接查,不就是最新记录了吗?
那来看看具体咋弄吧。
代码
首先第一步,找出每一个name对应的最新时间
select name, max(dtime) from test group by name;
+------+---------------------+
| name | max(dtime) |
+------+---------------------+
| xw | 2023-05-22 20:01:43 |
| ll | 2023-05-26 20:01:54 |
| oo | 2023-05-03 20:01:56 |
+------+---------------------+
而后我们只需要将上面查询的数据和表中的数据进行左连接即可
select t2.* from (select t.name, max(t.dtime) dtime from test t group by name) t1 left join test t2 on t1.name=t2.name and t1.dtime=t2.dtime;
+----+------+---------------------+------+
| id | name | dtime | info |
+----+------+---------------------+------+
| 2 | xw | 2023-05-22 20:01:43 | 5-22 |
| 5 | ll | 2023-05-26 20:01:54 | 5-26 |
| 6 | oo | 2023-05-03 20:01:56 | 5-03 |
+----+------+---------------------+------+
3 rows in set (0.07 sec)
-- Create table
create table TEST
(
id NUMBER,
name VARCHAR2(20),
dtime DATE,
info VARCHAR2(20)
)
;
insert into test (ID, NAME, DTIME, INFO)
values (1, 'xw', to_date('20-03-2024', 'dd-mm-yyyy'), '2');
insert into test (ID, NAME, DTIME, INFO)
values (2, 'xw', to_date('23-03-2024', 'dd-mm-yyyy'), '3');
insert into test (ID, NAME, DTIME, INFO)
values (3, 'xw', to_date('20-03-2024', 'dd-mm-yyyy'), '4');
insert into test (ID, NAME, DTIME, INFO)
values (4, 'll', to_date('19-03-2024', 'dd-mm-yyyy'), '5');
insert into test (ID, NAME, DTIME, INFO)
values (5, 'll', to_date('20-03-2024', 'dd-mm-yyyy'), '6');
insert into test (ID, NAME, DTIME, INFO)
values (6, 'oo', to_date('11-03-2024', 'dd-mm-yyyy'), '7');
insert into test (ID, NAME, DTIME, INFO)
values (7, 'oo', to_date('27-03-2024', 'dd-mm-yyyy'), '8');
-----方式1
select t.*, t.rowid from test t
--select t2.name from (select t1.* from test t1 order by dtime desc ) t2 group by t2.name
select name, max(dtime) from test group by name;
select t.*, t.rowid from test t
-----方式2
SELECT *
FROM (
SELECT ROW_NUMBER() OVER(
PARTITION BY name ORDER BY dtime DESC
) AS rid, test.*
FROM test
)
WHERE rid = 1;
select t2.* from (select t.name, max(t.dtime) dtime from test t group by name) t1 join test t2 on t1.name=t2.name and t1.dtime=t2.dtime;
-----方式3
mysql8.0之前没有类似oracle 中的row_number()函数,max min 这种只适用于ID列,或者唯一有序列的情况,所以采用这种方式
select a.* from test a where not exists(select 1 from test where name = a.name and dtime > a.dtime)
name是分组字段,dtime排序字段