查找特定投标人的所有获胜拍卖

时间:2014-05-09 21:38:37

标签: mysql

我们有两个用于存储拍卖的表格。它的出价信息。

拍卖(存储拍卖信息)

auction_id auction_name
---------- ---------------------
2216 Test Auction
...

auction_bid (存储竞价出价)

bid_id amount bidder auction_id
------ -------- ------ ------------
8398 50.0000 53 2216
8397 50.0000 32 2216
8396 20.0000 53 2216

...

注意:具有最高出价金额的出价工具被声明为获胜者。如果是平局出价,最后一个具有最大平局金额的投标人将被宣布为获胜者。 例如,在上述案例中,中标者为53

现在,我想在用户信息中心上显示所有获胜的拍卖信息。例如,对于bidder = 53 我为此目的使用了以下查询:

SELECT DISTINCT 
  a.*,
  b.bid_id,
  b.amount,
  b.bidder 
FROM
  auction a 
  LEFT JOIN auction_bid b 
    ON a.auction_id = b.auction_id 
WHERE b.bidder = 53 
  AND b.amount = 
  (SELECT 
    MAX(amount) 
  FROM
    auction_bid tmp 
  WHERE tmp.auction_id = b.auction_id 
  LIMIT 0, 1)

这适用于bidder = 53。 但对于竞价者= 32,同样的拍卖也显示为中奖拍卖。

我知道这个问题是由于平局出价造成的。如何修改上述查询以使其适用于平局出价? 任何帮助都非常感谢。

问候

3 个答案:

答案 0 :(得分:2)

为了提高效率,我会使用bid_id作为您的过滤器,并确保每次拍卖只能记录一条记录:

投标人53:

SELECT
  a.*,
  b.bid_id,
  b.amount,
  b.bidder 
FROM
  auction a 
  LEFT JOIN auction_bid b 
    ON a.auction_id = b.auction_id 
WHERE b.bidder = 53 
  AND b.bid_id = 
  (SELECT bid_id
   FROM auction_bid 
   WHERE auction_id = b.auction_id 
   ORDER BY amount desc,bid_id desc
   LIMIT 0,1);

结果:

AUCTION_ID    AUCTION_NAME    BID_ID    AMOUNT    BIDDER
----------    ------------    ------    ------    ------
2216          Test Auction    8398      50         53

投标人32:

SELECT
  a.*,
  b.bid_id,
  b.amount,
  b.bidder 
FROM
  auction a 
  LEFT JOIN auction_bid b 
    ON a.auction_id = b.auction_id 
WHERE b.bidder = 32 
  AND b.bid_id = 
  (SELECT bid_id
   FROM auction_bid 
   WHERE auction_id = b.auction_id 
   ORDER BY amount desc,bid_id desc
   LIMIT 0,1)

返回零行:http://www.sqlfiddle.com/#!2/beb2e3/6

答案 1 :(得分:1)

您可以尝试将此代码添加到查询的末尾:

AND NOT EXISTS (select * from auction_bid tmp2 where tmp2.auction_id=b.auction_id and tmp2.amount = b.amount AND tmp2.bid_id>b.bid_id)

这将检查以确保在给定出价后的同一拍卖中没有相同金额的出价(假设您告知稍后出价的方式是更高的bid_id)。

答案 2 :(得分:0)

试试这个:

SELECT DISTINCT 
  a.*,
  b.bid_id,
  b.amount,
  b.bidder 
FROM
  auction a 
  LEFT JOIN auction_bid b 
    ON a.auction_id = b.auction_id 
WHERE b.bidder = 53 
  AND b.amount = 
  (SELECT 
    MAX(amount) 
  FROM
    auction_bid tmp 
  WHERE tmp.auction_id = b.auction_id 
  LIMIT 0, 1)
GROUP BY b.bid_id
HAVING MAX(b.bid_id)



您也可以尝试这一点,但我无法确定这可以在没有测试的情况下运行:

SELECT
  a.*,
  b.bid_id,
  b.amount,
  b.bidder 
FROM
  auction AS a 
  LEFT JOIN auction_bid AS b 
    ON a.auction_id = b.auction_id 
WHERE b.bidder = 53 
GROUP BY b.bid_id
HAVING MAX(b.amout) AND MAX(b.bid_id);