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

时间:2023-03-09 10:01:55
mysql分组查询获取组内某字段最大的记录
id  sid  cid 
1   1    1
2   1    2
3   2    1 以sid分组,最后取cid最大的那一条,以上要取第2、3条 1 方法一:
select * from (select * from table order by cid desc) as a group by a.sid 方法二:
select a.* from table as a where cid = (select max(cid) from table where a.sid = sid) 方法三:
select a.* from table as a where not exists (select * from table where sid=a.sid and cid>a.cid) 方法四:
select a.* from table as a where exists (select count(*) from table where sid=a.sid and cid > a.cid having count(*)=0)

注:以上内容收集自网上