我有以下数据:

投标书

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


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

最佳答案

在低于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一起有趣的用法。

07-27 19:51