MySQL AND OR语句顺序

时间:2014-04-29 19:54:25

标签: mysql

我有下面的SQL语句,但我遇到了一个问题,我还没弄明白如何正确地订购WHERE语句。

当我运行这个语句时,它应该返回0,因为对于categoryid为2没有问题,并且只要我取出或者useranswers.level = 5就可以工作,因为还有其他类别id' s这是第5级。

所以我的问题是我需要在哪里提出或声明?

SELECT COUNT(*) FROM useranswers INNER JOIN users on useranswers.userid = users.id 
INNER JOIN kumiquestions on useranswers.questionid = kumiquestions.id 
WHERE login = 'chris3spice' 
and kumiquestions.categoryid = 2 and useranswers.level = 4 or useranswers.level = 5;

4 个答案:

答案 0 :(得分:0)

使用括号对相关条件进行分组。

答案 1 :(得分:0)

逻辑运算符具有优先权 - "和"最高的,然后"或"。 所以,你需要把paretheses,像这样

and kumiquestions.categoryid = 2 and (useranswers.level = 4 or useranswers.level = 5);

答案 2 :(得分:0)

两种解决方案:

SELECT COUNT(*) FROM useranswers INNER JOIN users on useranswers.userid = users.id 
INNER JOIN kumiquestions on useranswers.questionid = kumiquestions.id 
WHERE login = 'chris3spice' 
and kumiquestions.categoryid = 2 and (useranswers.level = 4 or useranswers.level = 5);

OR

SELECT COUNT(*) FROM useranswers INNER JOIN users on useranswers.userid = users.id 
INNER JOIN kumiquestions on useranswers.questionid = kumiquestions.id 
WHERE login = 'chris3spice' 
and kumiquestions.categoryid = 2 and useranswers.level IN (4, 5);

两者在逻辑上都是相同的。

答案 3 :(得分:0)

你可以写:

SELECT COUNT(*) FROM useranswers INNER JOIN users on useranswers.userid = users.id 
INNER JOIN kumiquestions on useranswers.questionid = kumiquestions.id 
WHERE login = 'chris3spice' 
and kumiquestions.categoryid = 2 and (useranswers.level = 4 or useranswers.level = 5);

如果您没有明确使用括号,则根据OR的位置自动完成分组,如下所示:

SELECT COUNT(*) FROM useranswers INNER JOIN users on useranswers.userid = users.id 
INNER JOIN kumiquestions on useranswers.questionid = kumiquestions.id 
WHERE (login = 'chris3spice' 
and kumiquestions.categoryid = 2 and useranswers.level = 4) or (useranswers.level = 5);

这就是为什么当你没有使用括号时你没有得到count(*)= 0。