How to write “not in ()” sql query using join

前端 未结 3 1603
小鲜肉
小鲜肉 2020-12-13 05:33

Could some one please provide how to write following sql query using joins. I do not want use not in as well as if possible I would like to replace

相关标签:
3条回答
  • 2020-12-13 06:21

    I would opt for NOT EXISTS in this case.

    SELECT D1.ShortCode
    FROM Domain1 D1
    WHERE NOT EXISTS
        (SELECT 'X'
         FROM Domain2 D2
         WHERE D2.ShortCode = D1.ShortCode
        )
    
    0 讨论(0)
  • 2020-12-13 06:31
    SELECT d1.Short_Code 
    FROM domain1 d1
    LEFT JOIN domain2 d2
    ON d1.Short_Code = d2.Short_Code
    WHERE d2.Short_Code IS NULL
    
    0 讨论(0)
  • 2020-12-13 06:35

    This article:

    • NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: SQL Server

    may be if interest to you.

    In a couple of words, this query:

    SELECT  d1.short_code
    FROM    domain1 d1
    LEFT JOIN
            domain2 d2
    ON      d2.short_code = d1.short_code
    WHERE   d2.short_code IS NULL
    

    will work but it is less efficient than a NOT NULL (or NOT EXISTS) construct.

    You can also use this:

    SELECT  short_code
    FROM    domain1
    EXCEPT
    SELECT  short_code
    FROM    domain2
    

    This is using neither NOT IN nor WHERE (and even no joins!), but this will remove all duplicates on domain1.short_code if any.

    0 讨论(0)
提交回复
热议问题