对于这种类型的查询,您希望从生成所有可能组合的“驱动程序”子查询开始。然后,您left outer join
对存在的内容执行 a,并选择不匹配的内容:
select driver.hid, driver.dept
from (select hid, dept
from (select distinct hid from hd) h cross join
(select distinct dept from hd) d
) driver left outer join
hd
on driver.hid = hd.hid and
driver.dept = hd.dept
where hd.hid is null;
编辑:
这是带有数据的更正查询:
with hd as (
select 5 as hid, 'neuro' as dept union all
select 2, 'derma' union all
select 3, 'cardio' union all
select 2, 'ent' union all
select 1, 'neuro' union all
select 5, 'optha' union all
select 3, 'ent' union all
select 3, 'optha' union all
select 4, 'derma' union all
select 1, 'optha' union all
select 5, 'derma'
)
select driver.hid, driver.dept
from (select hid, dept
from (select distinct hid from hd) h cross join
(select distinct dept from hd)d
) driver left outer join
hd
on driver.hid = hd.hid and
driver.dept = hd.dept
where hd.hid is null;
请注意,它返回的列表比问题中的要长。我认为该列表不完整。