[英]I hit a weird issue running a query against a PostgreSQL Database using NOT IN and don't understand why it didn't work
我有一个带有 id 和 parent_id 列的分层表,parent_id 有一个指向 id 列的外键。 每行只能有一个父级,但多行可以绑定到同一个父级。 我想检索所有没有孩子的行。
我尝试了以下查询
SELECT *
FROM table
WHERE id NOT IN (
SELECT DISTINCT(parent_id)
FROM table
)
这返回了 0 行。 如果我将NOT IN更改为IN ,它会正确返回具有子项的行(其他行通过它们的 parent_id 绑定到它)
我最终得到了这个工作:
SELECT *
FROM table
WHERE id NOT IN(
SELECT id
FROM table
WHERE id IN (
SELECT DISTINCT(parent_id)
FROM table
)
)
但我不明白为什么第一个查询不起作用? 谁能帮我理解这里发生了什么? 我不明白NOT IN应该如何工作吗?
尝试
SELECT *
FROM table
WHERE id NOT IN (
SELECT DISTINCT(parent_id)
FROM table
WHERE parent_id IS NOT NULL
)
例如:
with t(x) as (values(1),(2))
select 3
where 3 not in (select x from t);
┌──────────┐
│ ?column? │
├──────────┤
│ 3 │
└──────────┘
但
with t(x) as (values(1),(2),(null))
select 3
where 3 not in (select x from t);
┌──────────┐
│ ?column? │
├──────────┤
└──────────┘
这是因为 DBMS 无法做出决定是id = null
与否(结果undefined
)
您可以如上所述修复它或使用not exists
:
with t(x) as (values(1),(2),(null))
select 3
where not exists (select x from t where x = 3);
┌──────────┐
│ ?column? │
├──────────┤
│ 3 │
└──────────┘
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.