mysql从表

时间:2018-02-23 01:03:38

标签: php mysql greatest-n-per-group

我有拍卖系统的出价表:

BIDS

id user_id   bid   auction_id
1    3        1        1
2    4        2        1
3    4        1        1
4    3        3        1
5    3        2        1
6    3        2        1

我需要在给定的竞价中获得给定用户的最高用户出价(考虑到用户可能根本没有出价,直到该用户最后一次出价的出价总和)。

例如:

for user id=3, highest bid would be 11.
for user id=4, highest bid would be 4.
for user id=6, highest bid would be 0. (user didn't make any bids)

到目前为止,我有这个问题:

SELECT COALESCE( SUM( bid ), 0 ) as highest_bid
FROM BIDS
WHERE user_id = 3
AND auction_id = 1

但仅返回该用户所有出价的总和,并且我需要直到该用户最后出价的出价总和。

我希望我有道理。

谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个。基本上我得到每个用户的max_id并获得总和直到max_id。

我没有测试过这个。

SELECT
  user_id,
  (SELECT sum(bid)
   FROM BIDS
   WHERE id <= max_ids.id)
FROM
  (SELECT
     max(id) AS id,
     user_id
   FROM BIDS
   GROUP BY user_id) max_ids