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

来源:互联网 发布:淘宝店购物哪个软件好 编辑:程序博客网 时间:2024/05/01 12:24



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


方法
select * from (select * from table2 order by age desc) as agroup by a.table1_id

方法
select a.* from table2 as a where age = (select max(age) fromtable2 where a.table1_id=table1_id)

方法
select a.* from table2 as a where not exists (select * fromtable2 where table1_id=a.table1_id andage>a.age)

方法
select a.* from table2 as a where exists (select count(*) fromtable2 where table1_id=a.table1_id and age>a.agehaving count(*)=0)
1 0