1

在我的数据库中,当我运行以下查询时,我得到 1077 作为输出。

select count(distinct a_t1) from t1;

然后,当我运行这个查询时,我得到 459。

select count(distinct a_t1) from t1 
where a_t1 in (select a_t1 from t1 join t2 using (a_t1_t2) where a_t2=0); 

上面与此相同,此查询也给出 459:

select count(distinct a_t1) from t1 join t2 using (a_t1_t2) where a_t2=0

但是当我运行这个查询时,我得到的是 0 而不是我期望的 618:

select count(distinct a_t1) from t1 
where a_t1 not in (select a_t1 from t1 join t2 using (a_t1_t2) where a_t2=0);

我正在运行 PostgreSQL 9.1.5,这实际上可能没有必要。请指出我在上述查询中的错误。

更新 1: 我创建了一个新表并将上面子查询的结果输出到该表中。然后,我运行了一些查询:

select count(distinct a_t1) from t1
where a_t1 not in (select a_t1 from sub_query_table order by a_t1 limit 10);

万岁!现在我得到 10 作为答案!我能够将限制增加到 450。之后,我又开始得到 0。

更新 2:

sub_query_table 中有 459 个值。最后,这个查询给了我所需的答案:

select count(distinct a_t1) from t1
where a_t1 not in (select a_t1 from sub_query_table order by a_t1 limit 459);

作为这个,给出 0 作为答案:

select count(distinct a_t1) from t1
where a_t1 not in (select a_t1 from sub_query_table);

但是,为什么会这样?

4

1 回答 1

2

“NOT IN”运算符仅适用于“NOT NULL”。值为 null 的列不匹配。

select count(distinct a_t1) from t1 
where a_t1 not in (select a_t1 from t1 join t2 using (a_t1_t2) where a_t2=0) OR a_t1 IS NULL;
于 2012-09-24T04:18:51.413 回答