获取与MAX列关联的其他列

时间:2018-09-16 20:07:29

标签: mysql

我有以下数据:

BIDS

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

我的查询如下,但是没有返回正确的user_id。非代理最高出价为75100美元,但它返回的是user_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 

我已经研究了类似问题的其他解决方案,但到目前为止还无法解决任何问题。

2 个答案:

答案 0 :(得分:1)

在<8.0版的MySQL中(缺少窗口功能),您可以尝试以下操作:

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 

here说明了SUBSTRING_INDEXGROUP_CONCAT的有趣用法。

答案 1 :(得分: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
        , 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