mysql how to get 2nd highest value with group by and in a left join

与世无争的帅哥 提交于 2019-12-10 20:34:39

问题


(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??


回答1:


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.



来源:https://stackoverflow.com/questions/17765752/mysql-how-to-get-2nd-highest-value-with-group-by-and-in-a-left-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!