Select NOT IN multiple columns

前端 未结 4 1495
闹比i
闹比i 2020-12-12 18:03

I need to implement the following query:

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


        
4条回答
  •  眼角桃花
    2020-12-12 18:25

    Another mysteriously unknown RDBMS. Your Syntax is perfectly fine in PostgreSQL. Other query styles may perform faster (especially the NOT EXISTS variant or a LEFT JOIN), but your query is perfectly legit.

    Be aware of pitfalls with NOT IN, though, when involving any NULL values:

    • Find records where join doesn't exist

    Variant with LEFT JOIN:

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

    See @Michał's answer for the NOT EXISTS variant.
    A more detailed assessment of four basic variants:

    • Select rows which are not present in other table

提交回复
热议问题