Search code examples
sqlpostgresqlselectionmultiple-value

SQL - How to select records with value A but not B? (A and B belongs to different rows)


Suppose I have a table like below:

row_id  record_id   tag_id
1       1           2
2       1           3
3       2           2
4       2           4
5       3           2
6       3           3

I want to get those record_id which they have record with tag_id of value 2 but does not have 3, in this case, I want to get record_id 2. I can only think of a SQL statement with 3 selection but it seems bulky. Is there any simpler, faster way to achieve this? Thanks.

Edit:

The SQL I got:

SELECT record_id
FROM table_A 
WHERE record_id NOT IN (SELECT record_id 
                         FROM table_A 
                         WHERE record_id IN (SELECT record_id 
                                              FROM table_A 
                                              WHERE tag_id = 2) 
                         AND tag_id =3) 
AND record_id IN (SELECT record_id FROM table_A WHERE tag_id = 2) GROUP BY record_id

And each record_id may have 1 to any number of tag_id value.


Solution

  • This can be simply written as

    SELECT record_id FROM table_A WHERE tag_id = 2
    EXCEPT
    SELECT record_id FROM table_A WHERE tag_id = 3;