gpt4 book ai didi

MySQL:有没有办法有条件地 LEFT JOIN? (或类似的?)

转载 作者:可可西里 更新时间:2023-11-01 07:17:22 26 4
gpt4 key购买 nike

我正在编写查询以获取 products 表中的ALL 产品,以及每个产品的销售价格 IF a 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)

最佳答案

是的,您可以将条件移动到查询的 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()

关于MySQL:有没有办法有条件地 LEFT JOIN? (或类似的?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1686156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com