在 mySQL 查询中的 OR WHERE 和 AND
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17750098/
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
OR WHERE and AND in mySQL Query
提问by Curtis
Basically, I'm trying to get data from an SQL based on two different groups, t.type
has to equal single
and t.status
has to equal 1
but as for t.org
I want to it get both DUAL
and RA
, here's what I attempted to no avail.
基本上,我试图从基于两个不同组的 SQL 中获取数据,t.type
必须相等single
并且t.status
必须相等,1
但至于t.org
我想要它同时获取DUAL
和RA
,这是我尝试无济于事的方法。
SELECT
COUNT( p.tID )
FROM
ticket AS t
INNER JOIN
people AS p ON t.ID = p.tID
WHERE
t.type = 'single' AND t.status='1' AND t.org = 'RA' OR t.org = 'DUAL'
I'm pretty sure theirs a way to get this query working, just not in my head
我很确定他们是一种让这个查询工作的方法,只是不在我的脑海里
回答by eggyal
AND
has higher precedencethan OR
, so your existing expression is currently evaluated as:
AND
具有比更高的优先级OR
,因此您现有的表达式当前被评估为:
WHERE
(t.type = 'single' AND t.status='1' AND t.org = 'RA') OR t.org = 'DUAL'
To force alternative logic, one needs to include explicit parentheses:
要强制使用替代逻辑,需要包含显式括号:
WHERE
t.type = 'single' AND t.status='1' AND (t.org = 'RA' OR t.org = 'DUAL')
However, in this case, one can use MySQL's IN()
operator instead of OR
:
但是,在这种情况下,可以使用 MySQL 的IN()
运算符而不是OR
:
WHERE
t.type = 'single' AND t.status='1' AND t.org IN ('RA','DUAL')
回答by AeroX
You can use the IN condition:
您可以使用 IN 条件:
WHERE
t.type = 'single' AND t.status = '1' AND t.org IN ('RA','DUAL')
Or you can use brackets to group conditions:
或者您可以使用括号对条件进行分组:
WHERE
t.type = 'single' AND t.status = '1' AND (t.org = 'RA' OR t.org = 'DUAL')