4

我正在编写一个查询以获取表中的所有产品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)
4

2 回答 2

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()
于 2009-11-06T08:20:52.033 回答
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()
于 2009-11-06T08:21:44.213 回答