SQL Server - 不是

Mad*_* Zu 29 sql t-sql sql-server notin

我需要构建一个查询,它将向我显示表1中的记录,但不在表2中,基于make-model-serial数字组合.

我知道有4条记录不同,但我的查询总是空白.

SELECT  *  
FROM Table1 WHERE MAKE+MODEL+[Serial Number] NOT IN
(SELECT make+model+[serial number] FROM Table2)
Run Code Online (Sandbox Code Playgroud)

表1有5条记录.

当我将查询更改为时IN,我得到1条记录.我做错了NOT什么?

Dav*_*kle 42

这是因为NOT IN的工作原理.

为了避免这些麻烦(并且在许多情况下为了更快的查询),我总是喜欢NOT EXISTS:

SELECT  *  
FROM Table1 t1 
WHERE NOT EXISTS (
    SELECT * 
    FROM Table2 t2 
    WHERE t1.MAKE = t2.MAKE
    AND   t1.MODEL = t2.MODEL
    AND   t1.[Serial Number] = t2.[serial number]);
Run Code Online (Sandbox Code Playgroud)


Joe*_*lli 6

你可能最好单独比较字段,而不是连接字符串.

SELECT t1.*
    FROM Table1 t1
        LEFT JOIN Table2 t2
            ON t1.MAKE = t2.MAKE
                AND t1.MODEL = t2.MODEL
                AND t1.[serial number] = t2.[serial number]
    WHERE t2.MAKE IS NULL
Run Code Online (Sandbox Code Playgroud)