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

要求:获得按 table1_id 分组,并且取得 table2 中 age 最大的记录信息。

方法一:
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)

此条目发表在MySQL分类目录,贴了, , 标签。将固定链接加入收藏夹。

Mysql按字段分组取最大值记录》有一条回应

  1. 李春儿说:

    请博主继续发好贴,支持你

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注