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

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