Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What am I missing?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading