對於這種類型的查詢,你要開始一個「驅動程序」子查詢產生的所有可能的組合。然後,做一個left outer join
到存在的,並選擇不匹配的:
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;
注意它會返回一個比問題長的列表。我認爲這份名單不完整。
你怎麼知道它沒有? –