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)
- 为什么
(Total)
不等于 (Q1)
+ (Q2)
的总和?
- 为什么在第二个查询中必须是“
OR
”而不是“AND
”来获取 "correct" 值,而逻辑是相同的?这一定是微不足道的,但无法想象背后的逻辑。
基于 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;
我有一个 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)
- 为什么
(Total)
不等于(Q1)
+(Q2)
的总和? - 为什么在第二个查询中必须是“
OR
”而不是“AND
”来获取 "correct" 值,而逻辑是相同的?这一定是微不足道的,但无法想象背后的逻辑。
基于 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;