MySQL:有没有办法有条件地左连接? (或类似?)
我正在编写一个查询来获取 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
}
我意识到 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)
I'm writing a query to get ALL of the products in the products
table, and the sale price for each product IF a record exists for that item in the specials
table.
What I'm looking for is something like:
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
}
I realise MySQL is not a programming language, but is there a way to create a query that results in the logical equivalent of the above?
The result set should look like:
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以将条件移至查询的
JOIN ON
部分。Yes, you can move the condition to the
JOIN ON
part of the query.