[英]Why I am getting null result from a sql query even though the condition is true?
[英]Why does this PostgreSQL query result in 0 results even though I know there are
我的系统中有 2 个表:journal 和 journal_contribution。 两者都有一个字段 uuid 作为主键,并且 journal_contribution 包含字段 journal_uuid 以将其链接到期刊。 其他领域不重要。 journal 表有 461283 条记录,journal_contribution 有 336136 条记录。
我想确定我有多少期刊没有 journal_contribution 引用它们。
我的第一个想法是以下查询
select count(*)
from journal
where uuid not in
(select journal_uuid as uuid
from journal_contribution)
我知道这不是很好,但我很惊讶 2 分钟后我得到了 0 结果。 更重要的是,如果我在没有“not”的情况下运行相同的查询,我得到的结果是 124121。如果我从期刊总数中减去这个,我预计原始结果是 337162。
当我将代码更改为以下性能更高的版本时,我确实得到了正确的结果,但我想首先了解 0。 有人可以向我解释一下吗?
select count(*)
from journal
where not exists
(select 1
from journal_contribution jc
where jc.journal_uuid = journal.uuid)
这些查询是在运行 PostgreSQL 11 的 pgAdmin 4.21 中完成的
我强烈,强烈建议您不要在子查询中使用not in
。 原因很简单: NULL
值处理不直观。
正如您所观察到的,如果子查询返回的任何行是NULL
,则NOT IN
会过滤掉所有行。
有一个简单的选择: not exists
:
select count(*)
from journal j
where not exists (select 1
from journal_contribution jc
where jc.journal_uuid = j.uuid
);
此外,此查询可以使用journal_contribution(journal_uuid)
上的索引。 我猜有了这样的索引,这个查询会相当快。
显然子查询包含 NULL 值。
将查询更改为
select count(uuid)
from journal
where uuid not in
(select distinct journal_uuid as uuid
from journal_contribution
where journal_uuid is not null)
给出正确的结果
如果子查询包含 NULL,则在 SQL select 和“IN”子查询中回答了它给出结果的原因
EXISTS 运算符显然对 NULL 值没有问题
问题是“journal_contribution”表中的“journal_uuid”列可以为空。 尝试使用 IN 运算符时,NULL 值将始终不返回任何内容。 就像写像WHERE id = NULL
这样的东西不会返回任何东西。 另一个查询正在工作,因为您正在尝试比较“journal”表中的 uuid 值,如果我没记错,它是主键且不可为空
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.