Left Join - 尝试识别子记录不存在的实例,或者如果它们存在,填充满足特定条件的唯一记录

Left Join - attempting to identify instances where child records do not exist, or if they do exist, populate unique records meeting specific criteria

我正在尝试在 SQL 数据库中搜索子记录不存在的实例,或者如果它们存在,它们是特定类型(例如历史)并且不存在其他类型(例如当前) :

SELECT distinct parent.id FROM parenttable 
Left Join childtable On childtable.primarykey = parenttable.primarykey 
Where childtable.id is null

这会毫无问题地填充我所有没有子记录的父记录。但是,我还希望查询填充 只有 存在的子记录是历史记录的实例(例如 childtable.type = 'Historical')。到目前为止我还没能做到这一点。

你可以直接使用 not exists:

select p.id 
from parenttable p
where not exists (
    select 1
    from childtable c
    where c.primarykey = p.primarykey and c.type <> 'Historical'
)

这句话是:从 parent table 中获取所有没有 child 类型不是“历史”的记录 - parent 没有 child也满足这个条件

请试试这个(使用运算符 In):

SELECT id FROM parenttab WHERE primarykey NOT IN
(SELECT primarykey FROM childtable WHERE type<>'Historical'
 OR type IS NULL)

比在子查询中为每一行查找匹配更快