SQL Server:多个WHERE NOT EXISTS子句

时间:2018-12-17 21:15:46

标签: sql sql-server tsql not-exists

我在Load_Charges_IMPORT查询中有大约2600行没有插入到Load_Charges查询中。

我正在尝试确保没有添加重复的主键条目。主键在Load_Charges查询中建立为复合键(收费说明+收费金额)。 Load_Charges_IMPORT查询中未设置任何键,并且此数据是从excel文档中导入的。

您能告诉我我的代码是否有问题,为什么当我知道0 row(s) affected中有2600多个行时为什么得到Load_Charges_IMPORT的响应。

INSERT INTO Load_Charges
    SELECT *
    FROM Load_Charges_IMPORT
    WHERE 
        NOT EXISTS (SELECT [Load ID]
                    FROM Load_Charges
                    WHERE Load_Charges_IMPORT.[Load ID] = Load_Charges.[Load ID])
        AND NOT EXISTS (SELECT [Charge Description]
                        FROM Load_Charges
                        WHERE Load_Charges_IMPORT.[Charge Description] = Load_Charges.[Charge Description])
        AND NOT EXISTS (SELECT [Charged Amount] 
                        FROM Load_Charges
                        WHERE Load_Charges_IMPORT.[Charged Amount] = Load_Charges.[Charged Amount]);

2 个答案:

答案 0 :(得分:6)

您的EXISTS子句排除其中任一条件为TRUE的所有行,不仅排除所有条件为TRUE的行。试试这个:

INSERT INTO Load_Charges

SELECT *

FROM Load_Charges_IMPORT

WHERE NOT EXISTS (
    SELECT * 
    FROM Load_Charges 
    WHERE Load_Charges_IMPORT.[Load ID]=Load_Charges.[Load ID]
    AND Load_Charges_IMPORT.[Charge Description]=Load_Charges.[Charge Description]
    AND Load_Charges_IMPORT.[Charged Amount]=Load_Charges.[Charged Amount]);

答案 1 :(得分:1)

解决该问题的另一种方法是使用一系列LEFT JOIN,并使用WHERE子句排除任何匹配的记录。

这是一种较短的语法,并且避免使用子查询。

INSERT INTO Load_Charges
SELECT imp.*
FROM 
    Load_Charges_IMPORT imp
    LEFT JOIN Load_Charges load1 ON load1.[Load ID] = imp.[Load ID]
    LEFT JOIN Load_Charges load2 ON load2.[Charge Description] = imp.[Charge Description]
    LEFT JOIN Load_Charges load3 ON load3.[Charged Amount]= imp.[Charged Amount]
WHERE load1.[Load ID] IS NULL AND load2.[Load ID] IS NULL AND load3.[Load ID] IS NULL
;

NB:这假定[Load ID]是Load_Charges表中的不可为空的字段。如果不是,则可以在WHERE子句中使用任何其他非空字段。