[SOLVED] SQL – Different conditions on the same column


I’m trying to achieve something very similar to SQL – Multiple conditions where clause the same column

The difference is that I want two separate WHERE conditions:

 WHERE tag_id IN (1,2)
 OR tag_id IN (3,2)
 GROUP BY other_id HAVING COUNT(tag_id) = 2

This gives me all the records that I need, but also gives me records that have the tags 1 or 3 even when that record doesn’t have tag_id = 2. I know that my problem is in the OR condition, because if I do (1,2) and (3,2) separately, I get the expected results for each query.

What am I missing?


You could use:

SELECT other_id
FROM yourTable
GROUP BY other_id
HAVING COUNT(tag_id) = 2 AND              -- 2 tags
       (SUM(tag_id NOT IN (1, 2)) = 0 OR  -- either (1, 2)
        SUM(tag_id NOT IN (3, 2)) = 0);   -- or (3, 2)

Answered By – Tim Biegeleisen

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *