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

数据库原始数据如下:数据库名:tbl_clothers

需求是:按照type分组,并获取个分组中price中的最大值,解决sql如下:

方法一:

select * 
from (select type, name, price from tbl_clothers order by price desc) as a
  group by a.type;

方法二:

select a.* from tbl_clothers as a 
where price = (select max(price) from tbl_clothers where a.type=type)

方法三:

select a.* from tbl_clothers as a 
where not exists (select * from tbl_clothers where type=a.type and price>a.price)
# not exists意思是:在tbl_clothers中找不到比a的价格更大的值,也就是a的值应该是最大的价格。

方法四:

select a.* from tbl_clothers as a 
where exists (select count(*) from tbl_clothers where type=a.type and price>a.price having count(*)=0)

方法五:

select a.* from tbl_clothers a 
inner join (
select type,max(price) maxprice 
from tbl_clothers group by type) b on a.type=b.type and a.price=b.maxprice 
#order by a.type; 

 方法六:这个是比较直观的

SELECT MAX(update_time) AS update_time, fid
FROM new
GROUP BY fid
ORDER BY update_time DESC

SELECT *
FROM new
INNER JOIN user ON user.id = new.user_id
WHERE fid = ? AND update_time = ?

建立索引ALERT TABLE ADD INDEX update_fid (fid, updatetime)

 

有些语法可能会由于数据裤版本不同,会有差别。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值