我正在编写查询以获取products
表中的所有产品,并且每个产品的销售价格 IF 存在一条记录specials
表格中的该项目。
我正在寻找的是:
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 :(得分: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()
答案 1 :(得分: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()