【问题标题】:mysql how to get 2nd highest value with group by and in a left joinmysql如何通过分组和左连接获得第二高值
【发布时间】:2013-07-20 19:10:11
【问题描述】:
(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 值吗?

【问题讨论】:

  • 当您提出sql查询问题时,请考虑提供示例数据和基于它的所需输出。它可以帮助您更快、更准确地获得答案。

标签: mysql greatest-n-per-group


【解决方案1】:

首先,您根本不需要第三次加入。您可以在一次连接中进行计算:

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

   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 排序。然后取列表的第二个元素。一个缺点是该值被转换为字符串,即使它以数字开头。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2016-04-09
    • 2015-07-17
    • 2019-06-23
    • 1970-01-01
    相关资源
    最近更新 更多