使用多个EXISTS查询返回太多行

时间:2014-10-20 14:54:17

标签: sql sql-server tsql exists

原始表中有1466303条记录,我已将1108441条记录插入到单独的表中。我想知道的是剩下的数据是什么?所以我使用multiple exists查询剩下的数据:

SELECT SG_customer,
       PHONE,
       SG_Name,
       SG_Secondary_Address,
       SG_Primary_Address,
       SG_City,
       SG_State,
       SG_Zip,
       SG_Email
FROM   FMJ_DB_VPI_EXPANDED_DATA X
WHERE  NOT EXISTS (SELECT 1
                   FROM   FMJScore
                   WHERE  SGID = X.SG_Customer
                          AND Phone = X.Phone
                          AND Name = X.SG_Name
                          AND SecondAddress = X.SG_Secondary_Address
                          AND Address = X.SG_Primary_Address
                          AND City = X.SG_City
                          AND State = X.SG_State
                          AND Zip = X.SG_Zip
                          AND Email = X.SG_Email) 

运行它返回144391条记录,应该有357862的差异,我不明白为什么它会返回这么多记录。

1 个答案:

答案 0 :(得分:1)

我假设您希望null被视为等于null,我还假设''如果它被替换为通常不会发生的事情,则不用作值:

SELECT SG_customer,
   PHONE,
   SG_Name,
   SG_Secondary_Address,
   SG_Primary_Address,
   SG_City,
   SG_State,
   SG_Zip,
   SG_Email
FROM   FMJ_DB_VPI_EXPANDED_DATA X
WHERE  NOT EXISTS (SELECT 1
               FROM   FMJScore
               WHERE  coalesce(SGID,'') = coalesce(X.SG_Customer,'')
                      AND coalesce(Phone,'') = coalesce(X.Phone,'')
                      AND coalesce(Name,'') = coalesce(X.SG_Name,'')
                      AND coalesce(SecondAddress,'') = coalesce(X.SG_Secondary_Address,'')
                      AND coalesce(Address,'') = coalesce(X.SG_Primary_Address,'')
                      AND coalesce(City,'') = coalesce(X.SG_City,'')
                      AND coalesce(State,'') = coalesce(X.SG_State,'')
                      AND coalesce(Zip,'') = coalesce(X.SG_Zip,'')
                      AND coalesce(Email,'') = coalesce(X.SG_Email,''))

由于函数调用

,优化器可能无法有效地使用索引