我会运行什么SQL查询来获取我正在丢失的拍卖列表? (eBay示例)

时间:2011-05-21 21:56:38

标签: mysql sql

我会试着给出一个“eBay”的例子,我相信这是最简单的问题。

想象一下bids

的表格
bid_id | bid_from_user | bid_for_auction | bid_price
1      | 150           | 1               | 20
2      | 453           | 1               | 30
3      | 42            | 1               | 50
4      | 12            | 2               | 12
5      | 60            | 2               | 20

想象一下,您需要列出某个人当前正在竞标和失败的竞价。

因此,我们当前的用户ID为12,因此bid_from_user='12'

此用户目前正在以价格2对竞价标识12出价,并且显然正在失败,因为有另一个用户以相同的价格竞价同一拍卖。

我不想列出用户出价的所有拍卖,我只想列出用户出价失败的那些(=不是他赢的那些)。

那么,我要运行什么查询来执行此操作?

2 个答案:

答案 0 :(得分:7)

SELECT b.bid_id, b.bid_from_user, b.bid_for_auction, b.bid_price
  FROM bids b
 WHERE b.bid_from_user = '12'
   AND EXISTS (
           SELECT 1 
             FROM bids x 
            WHERE x.bid_for_auction = b.bid_for_auction
              AND x.bid_price > b.bid_price
              AND x.bid_from_user <> b.bid_from_user);

编辑:以上似乎是最清晰,最清晰的解决方案;但是这里有一个替代方案,允许MySQL传统上不能很好地处理子查询...

  SELECT b.bid_for_auction
    FROM bids b
         JOIN bids x ON x.bid_for_auction = b.bid_for_auction
     AND x.bid_price > b.bid_price
     AND x.bid_from_user <> b.bid_from_user
   WHERE b.bid_from_user = '12'
GROUP BY b.bid_for_auction;

答案 1 :(得分:1)

select中的值仅用于证明:

  SELECT MAX( a.bid_price ), a.bid_for_auction, b.bid_price
    FROM bids a 
         INNER JOIN bids b ON a.bid_for_auction = b.bid_for_auction
   WHERE b.bid_from_user = 12 
GROUP BY bid_for_auction
  HAVING b.bid_price < MAX(a.bid_price);