获取与max column关联的其他列

bihw5rsg  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(305)

我有以下数据:
投标

record_id    listing_id  user_id  amount   proxy
------------------------------------------------
43           26          3        75000    0
44           26          29       79100    1
45           26          29       75100    0

列表

record_id    reserve_price   start_price   user_id   status
-----------------------------------------------------------
26           80000           75000         2         0

我想返回与最大非代理出价金额相关联的行,即proxy=0
我的查询如下,但是它没有返回正确的用户id。非代理出价的最大值是$75100,但是它返回的用户id=3,这是不正确的。

select 
        IFNULL(MAX(b.amount),0) AS maxBid
        , IFNULL(l.reserve_price,0) as reserve_price
        , IFNULL(l.start_price,0) as start_price
        , b.user_id 
    from bids b 
     join listings l on l.record_id = b.listing_id 
     where b.listing_id = 26 
     and l.status = 0 
     and b.proxy <> 1 
     order by maxBid desc, high_bidder desc limit 1

我已经研究过解决类似问题的其他方法,但到目前为止还没有找到任何可行的方法。

vjrehmav

vjrehmav1#

在mysql版本<8.0(缺少窗口函数)中,可以尝试以下操作:

SELECT 
    IFNULL(MAX(b.amount),0) AS maxBid
    , IFNULL(l.reserve_price,0) as reserve_price
    , IFNULL(l.start_price,0) as start_price
    , SUBSTRING_INDEX(GROUP_CONCAT(DISTINCT b.user_id   
                                   ORDER BY b.amount DESC  
                                   SEPARATOR ','), 
                      ',', 
                      1) AS user_id 
FROM bids b 
JOIN listings l on l.record_id = b.listing_id 
WHERE b.listing_id = 26 
 and l.status = 0 
 and b.proxy <> 1 
GROUP BY b.listing_id

有趣的用法 SUBSTRING_INDEXGROUP_CONCAT 在这里解释。

mu0hgdu0

mu0hgdu02#

我想你只要把结果整理好就行了。你不是按数量排序结果的。-

select 
        IFNULL(MAX(b.amount),0) AS maxBid
        , IFNULL(l.reserve_price,0) as reserve_price
        , IFNULL(l.start_price,0) as start_price
        , b.user_id 
    from bids b 
     join listings l on l.record_id = b.listing_id 
     where b.listing_id = 26 
     and l.status = 0 
     and b.proxy <> 1 
     order by b.amount desc, maxBid desc, high_bidder desc limit 1

相关问题