Nic*_*ick 4 mysql join left-join
我正在编写查询以获取表中的所有产品products,并且每个产品的销售价格如果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
}
Run Code Online (Sandbox Code Playgroud)
我意识到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)
Run Code Online (Sandbox Code Playgroud)
是的,您可以将条件移动到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()
Run Code Online (Sandbox Code Playgroud)