Cesar Bielich
Cesar Bielich

Reputation: 4945

ambiguous mysql statement using AND and OR need help to structure correctly

I have a sql statement that I already know is not structured correctly using a SELECT with AND and OR. I have tried several variations but I can't seem to get it to work. It is returning 18 records when it should be returning only 17.

SELECT * 
FROM xxx_activity 
WHERE (dest_id = '20321' OR dest_id = 0) 
      AND user_id != '20321' 
      AND department_id = 14 
      OR department_id = 15 
      OR department_id = 16 
      AND read_test NOT LIKE '%|20321|%' 
      AND org_code = '20321'

Let me break down what I need

Any help to structure this correctly?

Upvotes: 0

Views: 33

Answers (2)

Rahul
Rahul

Reputation: 77866

You are probably not grouping your condition properly

WHERE dest_id in ('20321' ,'0') 
AND user_id != '20321' 
AND department_id in (14 , 15 , 16)
AND read_test NOT LIKE '%|20321|%' 
AND org_code = '20321'

Upvotes: 1

Bill Roberts
Bill Roberts

Reputation: 1171

You didn't mention conditions for code_org, but i think this is what you want:

SELECT
 * 
FROM
 xxx_activity
WHERE
 dest_id in ('20321' , '0')
AND
 user_id != '20321'
AND
 department_id in (14 , 15 , 16)
AND
 read_test NOT LIKE '%|20321|%'
AND
 org_code = '20321'

Upvotes: 1

Related Questions