码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2017-05-22 13:38:16      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:blog   tab   最大   记录   bsp   and   sina   having   count   

技术分享

 
要求:获得按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)

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

标签:blog   tab   最大   记录   bsp   and   sina   having   count   

原文地址:http://www.cnblogs.com/xiaowufile/p/6888899.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!