2009-11-06 58 views
4

我正在寫一個查詢來獲取產品的ALLproducts表,銷售價格爲每個產品IF一個記錄存在於specials表項。MySQL:有沒有一種方法有條件地進行LEFT JOIN? (或類似?)

我正在尋找的是這樣的:

SELECT * FROM products P 
IF (S.specials_date_available <= NOW() AND S.expires_date > NOW()) 
{ // The sale has started, but has not yet expired 
    LEFT JOIN specials S 
     ON P.products_id = S.products_id 
} 

我知道MySQL是不是一種編程語言,但有一個方法來創建一個查詢,導致上面的邏輯等價物?

結果集應該是這樣的:

ID Name   Price  Sale Price 
1  Widget A  10.00  (empty, because this item has no sale record) 
2  Widget B  20.00  15.45 (this item is currently on sale) 
3  Widget C  22.00  (empty - this item was on sale but the sale expired) 
+0

一個別名的定義如下:collumn_name __AS__別名 – NDM 2009-11-06 08:22:58

+0

這些表別名,而不是列的別名。大多數(所有?)數據庫引擎都具有可選的AS關鍵字。 – 2009-11-06 08:24:15

回答

9

是的,你可以移動的條件查詢的JOIN ON一部分。

SELECT * 
FROM products P 
LEFT JOIN specials S 
    ON P.products_id = S.products_id AND 
     S.specials_date_available <= NOW() AND 
     S.expires_date > NOW() 
+0

謝謝!工作很好。 – Nick 2009-11-06 08:47:35

1
SELECT * FROM products P 
    LEFT JOIN specials S 
    ON P.products_id = S.products_id AND S.specials_date_available <= NOW() AND S.expires_date > NOW() 
相關問題