mysql 左连接 group by,mysql如何通过group by和在左连接中获得第二高的值

(select id from owner where date_format(auction_date,'%Y-%m-%d %H:%i:00') = date_format(NOW(),'%Y-%m-%d %H:%i:00')) as a

left join (select owner_id,max(nb) as maxbid from auction group by owner_id) as b on a.id=b.owner_id

left join (select owner_id,max(mb) as maxautobid from auction group by owner_id) as c on a.id=c.owner_id

For the second left join statement, i'm able to get the highest mb value. Can someone help me add a third left join statement so that i can get the second highest mb value??

解决方案

First, you don't need a third join at all. You can do your calculation in one join:

from (select id

from owner

where date_format(auction_date,'%Y-%m-%d %H:%i:00') = date_format(NOW(),'%Y-%m-%d %H:%i:00')

) as a left join

(select owner_id, max(nb) as maxbid, max(mb) as maxautobi

from auction

group by owner_id

) b

on a.id=b.owner_id;

Getting the second largest value for mb then uses a trick, involving substring_index() and group_concat():

from (select id

from owner

where date_format(auction_date,'%Y-%m-%d %H:%i:00') = date_format(NOW(),'%Y-%m-%d %H:%i:00')

) as a left join

(select owner_id, max(nb) as maxbid, max(mb) as maxautobi,

substring_index(substring_index(group_concat(mb order by mb desc), ',', 2), ',', -1

) as second_mb

from auction

group by owner_id

) b

on a.id=b.owner_id;

The idea is to concatenate the values together, ordering by mb. Then take the second element of the list. The one downside is that the value is converted to a character string, even when it starts as a number.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值