MySQL - 在哪里或?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17953542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL - Where Or?
提问by Necro.
I have a MySQL statement where I'm trying to exclude statements depending on where they "belong to" The query goes through, but it still shows the rows that I specifically said where its not equal to?
我有一个 MySQL 语句,我试图根据它们“属于”的位置来排除语句 查询通过,但它仍然显示我特别指出的行不等于?
SELECT id, belongsto, title, madeby, sticky, locked, lastpost, posts
FROM threads
WHERE sticky !=1
AND belongsto !=12 OR sticky !=1 AND belongsto !=13
ORDER BY `threads`.`date` DESC
LIMIT 20
回答by John Conde
You need parenthesis around your OR
statements to group them together logically.
您需要在OR
语句周围加上括号,以便在逻辑上将它们组合在一起。
WHERE sticky !=1
AND belongsto !=12 OR sticky !=1 AND belongsto !=13
should be:
应该:
WHERE (sticky !=1 AND belongsto !=12)
OR (sticky !=1 AND belongsto !=13)
or better yet:
或者更好:
WHERE sticky !=1 AND belongsto NOT IN(12,13)
回答by spencer7593
If the goal is to exclude rows with belongsto values of 12
and 13
, then the OR
should be replaced with AND
.
如果目标是排除属于12
和的值的行13
,则OR
应替换为AND
。
The assertion (in the selected answer) that parentheses are "missing" and need to be added, is wrong. The addition of parentheses does not change the change the statement. The AND
operator already has a higher precedence than the OR
operator.)
括号“缺失”并需要添加的断言(在所选答案中)是错误的。添加括号不会改变语句的变化。该AND
运营商已经拥有比一个更高的优先级OR
运营商。)
WHERE sticky !=1
AND belongsto !=12 AND sticky !=1 AND belongsto !=13
^^^
Because it's unnecessary to repeat the same predicate twice, this could be rewritten as:
因为没有必要重复相同的谓词两次,这可以改写为:
WHERE sticky !=1
AND belongsto !=12 AND belongsto !=13
Which can also be written as:
也可以写成:
WHERE sticky !=1
AND NOT (belongsto =12 OR belongsto =13)
This can also be rewritten using a NOT IN (12,13)
(as demonstrated in the selected answer).
这也可以使用 a 重写NOT IN (12,13)
(如所选答案中所示)。