这两个查询的区别(EXISTS与NOT LIKE和NOT EXISTS与LIKE)

时间:2015-10-26 09:07:56

标签: sql sql-server tsql subquery

我很难理解这两个查询之间的区别。不会给出相同的输出,只是结果略有不同。这两个问题不一样,但只是倒置了吗?您可以在最后一个子查询中看到差异。

SELECT *
FROM[dbo].[MNO International AB$Item] t1
WHERE 
    t1.[Item Type] = 0
    AND (
            NOT EXISTS(SELECT * FROM [dbo].[MNO International AB$Item Cross Reference] t2 WHERE t2.[Item No_] = t1.No_ AND t2.[Cross-Reference Type No_] = 'EAN13' AND t2.[Cross-Reference No_] <> '' AND t2.[Cross-Reference Type] = 3)
            OR t1.[Statistics Group] = 0
        ) --Result: 2178

    AND NOT EXISTS 
                (SELECT * FROM [dbo].[MNO International AB$Master] t2 
                 WHERE t1.[Master No_] = t2.No_ 
                 AND t2.[Collection No_] LIKE 'NEW-NOS'
                 )

另一个查询

SELECT *
FROM[dbo].[MNO International AB$Item] t1
WHERE 
    t1.[Item Type] = 0
    AND (
            NOT EXISTS(SELECT * FROM [dbo].[MNO International AB$Item Cross Reference] t2 WHERE t2.[Item No_] = t1.No_ AND t2.[Cross-Reference Type No_] = 'EAN13' AND t2.[Cross-Reference No_] <> '' AND t2.[Cross-Reference Type] = 3)
            OR t1.[Statistics Group] = 0
        ) --Result: 2178

    AND EXISTS 
                (SELECT * FROM [dbo].[MNO International AB$Master] t2 
                 WHERE t1.[Master No_] = t2.No_ 
                 AND t2.[Collection No_] NOT LIKE 'NEW-NOS'
                 )

1 个答案:

答案 0 :(得分:2)

我认为结果不一样。这是因为:

NOT(A = B AND C <> D)
= NOT(A = B) OR NOT(C <> D)
= A <> B OR C = D

返回您的查询:

NOT EXISTS (t1.[Master No_] = t2.No_ AND t2.[Collection No_] NOT LIKE 'NEW-NOS')
= EXISTS (t1.[Master No_] <> t2.No_ OR t2.[Collection No_] LIKE 'NEW-NOS')