T-SQL多重否定条件

时间:2016-10-13 09:48:04

标签: tsql conditional sql-server-2016

我的表格A85337(Total)

然后是以下查询(Q1)

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

返回590行。

下一个查询(Q2)

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

返回:44245行。 (应返回84747)

  • 为什么(Total)不等于(Q1) + (Q2)的总和?
  • 为什么第二个查询必须是“OR”而不是“AND”才能在逻辑相同时获得“正确”值?它必须是微不足道的,但无法想象背后的逻辑。

2 个答案:

答案 0 :(得分:0)

基于否定的De Morgan's laws

var mongoose = require('mongoose');

db.getCollection('Users').find({}).forEach(function(item){
  if (item.Ancestors instanceof Array){
      var tmp = new Array()
      item.Ancestors.forEach(function(ancestor){
          if (ancestor instanceof String){
               tmp.push(mongoose.Types.ObjectId(ancestor))
             }
          })
          item.Ancestors = tmp
          db.getCollection('Users').save(item) 
  }
})

答案 1 :(得分:0)

这是因为在您使用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;