mysql按字段分组,取最大值记录.

本文介绍四种SQL方法,用于从数据库中选取按table1_id分组后的每组中age字段的最大值记录。这四种方法分别使用子查询、自连接、NOT EXISTS和EXISTS条件来实现目标,为开发者提供了多种解决同一问题的角度。

要求:获得按table1_id分组,并且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)

 

 

 

 

转自:http://blog.sina.com.cn/s/blog_8155e74d0101g1pl.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值