Mysql按字段分组取最大值记录

时间:2022-02-09 01:15:14

Mysql按字段分组取最大值记录
要求:获得按table1_id分组,并且age最大的记录信息,即2、3、5条

方法 select * from (select * from table2 order by age desc) as a group by a.table1_id
方法 select a.* from table2 as a where age = (select max(age) from table2 where a.table1_id=table1_id)
方法 select a.* from table2 as a where not exists (select * from table2 where table1_id=a.table1_id and age>a.age)
方法 select a.* from table2 as a where exists (select count(*) from table2 where table1_id=a.table1_id and age>a.age having count(*)=0)
参考资源:http://blog.sina.com.cn/s/blog_8155e74d0101g1pl.html