我需要有关 sql 查询的帮助。
我有两张桌子Person_Table
和PersonAlias_Table
。在第一个表中, person_id和uniqe_id是主键,在别名表中, person_id和 uniqe_id 以及activity_code也是主键。我想找到在 Alias 表中但不在 person 表中的数据。
select *
from PersonAlias_Table PA
left outer join Person_Table P on PA.person_id = P.person_id
and PA.uniqe_id = P.uniqe_id
where P.uniqe_id is null
试试这个
执行此操作的最佳方法取决于您的 DBMS,您可以使用NOT EXISTS
或LEFT JOIN/IS NULL
不存在
SELECT *
FROM PersonAlias_Table pat
WHERE NOT EXISTS
( SELECT 1
FROM Person_Table pt
WHERE pt.Person_ID = pat.Person_ID
AND pt.Uniqe_ID = pat.Uniqe_ID
)
左连接/为空
SELECT *
FROM PersonAlias_Table pat
LEFT JOIN Person_Table pt
ON pt.Person_ID = pat.Person_ID
AND pt.Uniqe_ID = pat.Uniqe_ID
WHERE pt.Person_ID IS NULL
According to this answer in MySQL NOT EXISTS
is a little bit less efficient, In SQL Server LEFT JOIN / IS NULL
is less efficient, in PostgreSQL and Oracle both methods are the same, so it is really personal preference.