Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL "IN" statement for multiple columns

Tags:

sql

distinct

I would like to filter Name,X combinations for which is never X=Y Let's assume the following table:

*Name*     *X*      *Y*
   A        2        1
   A        2        2   <--- fulfills requirement for Name=A, X=2
   A       10        1
   A       10        2
   B        3        1
   B        3        3   <--- fulfills requirement for Name=B, X=3
   B        1        1   <--- fulfills requirement for Name=B, X=1
   B        1        3

So I would like to return the combination Name=A, X=10 for which X=Y is never true. This was my approach (which is syntactically incorrect)

SELECT * 
FROM TABLE 
WHERE NAME
     , X NOT IN (SELECT DISTINCT NAME
                       , X 
                 FROM TABLE 
                 WHERE X=Y)

My problem is the where statement which cannot handle multiple columns. Does anyone know how to do this?

like image 935
user3726374 Avatar asked Dec 15 '22 21:12

user3726374


1 Answers

Just put the columns into parentheses

SELECT * 
FROM TABLE 
WHERE (NAME, X) NOT IN (SELECT NAME, X 
                        FROM TABLE WHERE X=Y);

The above is ANSI standard SQL but not all DBMS support this syntax though.

A distinct is not necessary for a sub-query for IN or NOT IN.

However NOT EXISTS with a co-related sub-query is very often faster that an NOT IN condition.

like image 108
a_horse_with_no_name Avatar answered Jan 15 '23 21:01

a_horse_with_no_name