mysql分组查询获取组内某字段最大的记录

本文介绍了四种不同的方法来实现SQL中选取特定分组内的最大值记录,适用于需要从每个分组中挑选出具有最大CID值的数据场景。
id  sid  cid 
1   1    1
2   1    2
3   2    1

以sid分组,最后取cid最大的那一条,以上要取第2、3条

1
方法一: 2 select * from (select * from table order by cid desc) as a group by a.sid 3 4 方法二: 5 select a.* from table as a where cid = (select max(cid) from table where a.sid = sid) 6 7 方法三: 8 select a.* from table as a where not exists (select * from table where sid=a.sid and cid>a.cid) 9 10 方法四: 11 select a.* from table as a where exists (select count(*) from table where sid=a.sid and cid > a.cid having count(*)=0)

 

注:以上内容收集自网上

 

转载于:https://www.cnblogs.com/thingk/p/4387380.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值