![](/img/trans.png)
[英]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.