"NOT IN" Postgres 的正确使用方法

Correct way to use "NOT IN" Postgres

我有两个表,People 和 Vehicles。车是人的。我正在尝试检查一个人是否没有车辆。我试图通过加入人员和车辆并显示不在 Vehicles.person_id.

中的人员 ID 来做到这一点

这没有返回任何内容,让我想知道我是否做错了什么,或者是否有更有效的方法。

查询如下

Select People.id From People INNER JOIN Vehicles on People.id=Vehicles.person_id where People.id NOT IN Vehicles.person_id;

使用子查询如下:

Select id 
From People
WHERE id NOT IN (SELECT distinct person_id
                 FROM Vehicles 
                 WHERE  person_id IS NOT NULL)

select all people who are not in (by Select id From People WHERE id NOT IN) all the people who has vehicle by SELECT distinct person_id FROM Vehicles (如果你愿意,你也可以在这里避免 null ).

另一个解决方案,使用集合:

Select id From People
except
SELECT person_id FROM Vehicles

用left join算出没有车的人

  Select distinct People.id 
  From People 
  LEFT JOIN Vehicles on        People.id=Vehicles.person_id 
  where Vehicles.person_id is NULL
如果子查询非常大,

NOT IN 可以有 issues with NULL values, and should probably be avoided for performance reasons

尝试 NOT EXISTS:

SELECT p.id
FROM People p
WHERE NOT EXISTS (
    SELECT 1 
    FROM Vehicles v
    WHERE v.person_id = p.id)