mysql如何通过group by和在左连接中获得第二高的值 [英] mysql how to get 2nd highest value with group by and in a left join

查看:380
本文介绍了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

对于第二个左连接语句,我能够获得最高的mb值.有人可以帮我添加第三个左连接语句,以便获得第二高的mb值吗?

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;

获取mb的第二个最大值,然后使用一个技巧,涉及到substring_index()group_concat():

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;

想法是将值连接在一起,按mb排序.然后使用列表的第二个元素.不利之处在于,即使该值以数字开头,该值也将转换为字符串.

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.

这篇关于mysql如何通过group by和在左连接中获得第二高的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆