Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

sql - OR WHERE and AND in mySQL Query

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

AND has higher precedence than OR, so your existing expression is currently evaluated as:

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:

WHERE 
    t.type = 'single' AND t.status='1' AND t.org IN ('RA','DUAL')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...