Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OR WHERE and AND in mySQL Query

Tags:

sql

mysql

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

like image 862
Curtis Avatar asked Jul 19 '13 15:07

Curtis


2 Answers

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')
like image 180
eggyal Avatar answered Sep 30 '22 18:09

eggyal


You can use the IN condition:

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')
like image 28
AeroX Avatar answered Sep 30 '22 16:09

AeroX