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 @   biangj  阅读(3055)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
点击右上角即可分享
微信分享提示