我有一个简单的拍卖数据库。它包括一个包含出价的表格。
+---------+---------+--------+------------+
| item_id | user_id | amount | time |
+---------+---------+--------+------------+
| 3 | 2 | 500 | 1540152972 |
| 3 | 4 | 500 | 1540151466 |
+---------+---------+--------+------------+
在拍卖结束时,我需要找出哪些用户赢得了哪些元素(最高金额)。我已经考虑过以下查询
SELECT item_id, user_id, MAX(amount)
FROM auction_bids
GROUP BY item_id
这似乎工作正常,直到多个用户以相同的金额出价。
在这种情况下,我需要检索最早的一个(即:最低的时间
值)。
如何将其应用到我的 GROUP BY
查询中?
最佳答案
如果具有相同 item_id 的其他行没有更高的价格,则返回一行,或者如果价格相同,则另一行更晚。
SELECT item_id, user_id, amount
FROM auction_bids a1
WHERE NOT EXISTS (select 1 from auction_bids a2
where a2.item_id = a1.item_id
and (a2.amount > a1.amount
or (a2.amount = a1.amount and a2.time < a1.time)))
关于mysql - 使用 MAX() 函数获得相等值的附加条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52919520/