mysql分组查询取第一条

查询前提条件是需要唯一ID和排序字段 

比如

select id,code,create_date from test;

需要用到的函数:

group_concat  分组连接

substring_index  按索引截取

 

插入四条记录:

insert into test(id,code,create_date)values('1','aa',now());

insert into test(id,code,create_date)values('3','aa',now());

insert into test(id,code,create_date)values('2','bb',now());

insert into test(id,code,create_date)values('4','bb',now());

 

 

按code分组,汇总ID集合:

select GROUP_CONCAT(id order by code,create_date desc) from test group by code;

 

 

 取第一个ID:

select substring_index(GROUP_CONCAT(id order by code,create_date desc),',',1) from test group by code;

 

 

 

 查询按code分组,最后的记录:

select * from test where id in(
select substring_index(GROUP_CONCAT(id order by code,create_date desc),',',1) from test group by code
);

 

posted @ 2022-10-17 11:35  biangj  阅读(3120)  评论(0)    收藏  举报