T-SQL 多重否定 Where 条件

T-SQL Multiple Negative Where Conditions

我有一个 table A,其中有 85337(Total)

然后进行如下查询(Q1)

SELECT  *
FROM    A
WHERE   1 = 1
        AND c1 = 0
        AND c2 = 0
        AND c3 = 0
        AND c4 = 0;

returns 590 行。

下一个查询(Q2)

SELECT  *
FROM    A
WHERE   1 = 1
        AND c1 != 0
        AND c2 != 0
        AND c3 != 0
        AND c4 != 0;

returns:44245 行。 (应该return84747)

基于 De Morgan's laws 否定:

NOT (P AND Q) => (NOT P OR NOT Q)

这是因为您的两个查询并没有像您使用的那样封装所有可能的数据组合 AND:

declare @a table (c1 int,c2 int,c3 int,c4 int);
insert into @a values
 (1,1,1,1)
,(0,0,1,1)  -- This row is not returned as it doesn't meet either criteria below
,(0,0,0,0)
,(0,0,0,0);

SELECT  *
FROM    @a
WHERE   1 = 1
        AND c1 = 0
        AND c2 = 0
        AND c3 = 0
        AND c4 = 0;

SELECT  *
FROM    @a
WHERE   1 = 1
        AND c1 != 0
        AND c2 != 0
        AND c3 != 0
        AND c4 != 0;