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

来源:互联网 发布:数据堂兼职怎么做 编辑:程序博客网 时间:2024/05/01 09:29

这里写图片描述

要求:获得按table1_id分组,并且age最大的记录信息,即2、3、5条
注意:不要轻易在MySQL中使用,MySQL中的DESC排序是一个假排序

方法一:

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://www.haogongju.net/art/1713263

1 0
原创粉丝点击