如何在多个 Where 子句之间 MySQL

How to MySQL Between Multiple Where Clause

我想显示价格在 10k 到 30k 之间的产品 category_id = 1,或 category_id = 2。

这是我的查询

SELECT * FROM products
WHERE price BETWEEN 10000 AND 30000
AND
category_id = '2' OR category_id = '3'
ORDER BY name ASC, price ASC

但我得到了这些类别中的所有产品,没有得到价格在 10k 到 30k 之间的产品

你还要考虑一下你对这个的操作顺序,你要这个

WHERE (price BETWEEN 10000 AND 30000)
AND
(category_id = '2' OR category_id = '3')

用合适的括号加强逻辑

SELECT * FROM products
WHERE price BETWEEN 10000 AND 30000
AND
(category_id = '2' OR category_id = '3')
ORDER BY name ASC, price ASC

您的 OR 谓词需要在括号之间:

SELECT * FROM products
WHERE price BETWEEN 10000 AND 30000
AND (category_id = '1' OR category_id = '2')
ORDER BY name ASC, price ASC

或者,您可以使用 IN:

SELECT * FROM products
WHERE price BETWEEN 10000 AND 30000
AND category_id IN ('1', '2')
ORDER BY name ASC, price ASC

要了解发生这种情况的原因,您需要了解 operator precedence。您可能记得在学校(我几乎不记得)乘法和除法在加法之前计算 - 这里的概念相同。

最好的做法(为了代码的可读性和明确您的意图)是使用括号强制按照您希望的顺序计算运算符。