Bootstrap

mysql 分组取最大最小一条(经典问题,有好的方法可以博客留言),与君共勉

  • 方法1:
select a.* from tb a 
where val = (select max(val) from tb where name = a.name) 
order by a.name

或者(这种可以控制取第几条,如最大第一条,第二条,第三条最后一条等等)

select a.* from tb a 
where val = (select val from tb where name = a.name order by val limit 0,1) 
order by a.name
  • 方法2:
select a.* from tb a 
where not exists
(select 1 from tb where name = a.name and val > a.val)
  • 方法3:
select a.* from tb a,
(select name,max(val) val from tb group by name) b 
where 
a.name = b.name 
and a.val = b.val 
order by a.name
  • 方法4:
select a.* 
from tb a inner join 
(select name , max(val) val from tb group by name) b 
on a.name = b.name and a.val = b.val 
order by a.name
  • 方法5
select a.* from tb a 
where 
1 > (select count(*) from tb where name = a.name and val > a.val )
 order by a.name

注意:子查询中的结果类型,作为条件匹配主语句,会有索引失效导致长时间匹配问题,不同可类型转换成一致,如方法一=匹配(这里是一致的),不一致请转化,其他类似。
如方法一:

select a.* from tb a 
where val = (select max(CAST(val AS SIGNED)) as val from tb where name = a.name) 
order by a.name
;