Select NOT IN Multiple Columns

I need to execute the following query

SELECT * FROM friend WHERE ( friend.id1, friend.id2 ) NOT IN (SELECT id1, id2 FROM likes) 

but NOT IN cannot be implemented on multiple columns. How to write this request

+43
sql database multiple-columns
Nov 07 2018-11-11T00:
source share
3 answers

I'm not sure if you are thinking about:

 select * from friend f where not exists ( select 1 from likes l where f.id1 = l.id and f.id2 = l.id2 ) 

it only works if id1 is associated with id1 and id2 with id2 not both.

+67
Nov 07 '11 at 7:12
source share
— -

Another mysteriously unknown RDBMS. Your syntax is great for PostgreSQL. Other query styles may be faster (especially the NOT EXISTS or LEFT JOIN option), but your query is completely correct.

Remember traps with NOT IN , although when using any NULL values:

  • Find records in which the connection does not exist

Option with LEFT JOIN:

 SELECT * FROM friend f LEFT JOIN likes l USING (id1, id2) WHERE l.id1 IS NULL; 

See @ Michał answer for the NOT EXISTS option.
A more detailed assessment of the four main options:

  • Select rows not in another table.
+14
Nov 07 '11 at 7:18
source share

You should probably use NOT EXISTS for multiple columns.

0
Nov 07 '11 at 7:10
source share



All Articles