Mysql查询使用where子句返回错误的数据

时间:2017-02-08 04:02:49

标签: mysql sql

我使用以下查询从mysql数据库中获取数据,我得到错误的数据。我希望得到cart_Status为2或3且view_Status为1的所有数据:

SELECT * FROM `cart` WHERE `view_Status` = 1 AND cart_Status = 2 OR `cart_Status` = 3

这就是我的数据结构和表格的样子:

enter image description here

但结果是,无论view_Status = 1是什么,它都会返回一些不是我的目标。

它返回:

enter image description here

当然,它不应该返回任何东西!但是,确实如此!

4 个答案:

答案 0 :(得分:3)

这是关于运营商的优先权 您的查询评估为

SELECT * FROM `cart` WHERE (`view_Status` = 1 AND cart_Status = 2) OR `cart_Status` = 3

您应该添加括号:

SELECT * FROM `cart` WHERE `view_Status` = 1 AND (cart_Status = 2 OR `cart_Status` = 3)

答案 1 :(得分:2)

SELECT * FROM `cart` WHERE `view_Status` = 1 AND (cart_Status = 2 OR `cart_Status` = 3)

或更好

SELECT * FROM `cart` WHERE `view_Status` = 1 AND cart_Status in (2, 3);

答案 2 :(得分:1)

您似乎在学习SQL。在WHERE子句中使用括号,尤其是当您混合ANDOR时。

但是,在您的情况下,IN是更好的解决方案:

SELECT c.*
FROM `cart` c
WHERE c.view_Status = 1 AND cart_Status IN (2, 3);

答案 3 :(得分:1)

运营商优先级存在问题。通常AND在编程语言中OR之前执行(从AND开始考虑比特的乘法,并且OR添加比特并且优先级变得熟悉)。所以,你的条件:

`view_Status` = 1 AND cart_Status = 2 OR `cart_Status` = 3

解析如下:

(`view_Status` = 1 AND cart_Status = 2) OR `cart_Status` = 3

会导致选择具有特定cart_Status的所有行。您必须在第二个子句周围添加括号:

`view_Status` = 1 AND (cart_Status = 2 OR `cart_Status` = 3)

或者更短:

`view_Status` = 1 AND cart_Status IN (2, 3)