2011-05-21 35 views
2

我會嘗試給出一個「eBay」示例,我相信這將是最簡單的方法。我會運行什麼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'

目前該用戶正在競標拍賣的ID 2與價格12和明顯失去,因爲有在同一拍賣的另一用戶投標具有更高的性價比。

我不想列出用戶所投標的所有拍賣,我只想列出那些用戶在上失敗(=不是他獲勝的那些)。

那麼,我跑什麼樣的查詢來做到這一點?

+0

這只是選擇用戶行不在拍賣的最大分組數 – shevski 2011-05-21 22:17:09

回答

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

什麼是「select 1」 – shevski 2011-05-21 22:18:26

+0

確切的 - 什麼是「select 1」? – 2011-05-21 22:32:24

+0

'1'讓'EXISTS'知道_something_被子查詢返回。 '1'可以是任何你喜歡的東西,例如'42'甚至'NULL'。 – bernie 2011-05-21 22:46:43

1

在選擇的值只爲證明:

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); 
相關問題