为了避免神奇的数字 99:
SELECT
P.pid
FROM
(
SELECT DISTINCT
Pi.pid, M.Director
FROM Production Pi
JOIN Movie M ON Pi.mid = M.mid
) P
GROUP BY
P.pid
HAVING
COUNT(p.Director) = 2 -- The directors should be exactly 2
AND MIN(CASE WHEN p.Director in ('Ben Affleck', 'Peter Jackson')
THEN 1 ELSE 0 END) = 1
其他方法:http ://www.anicehumble.com/2019/04/not-every-rdbms-has-every.html
请注意,not in
不能使用双重方法。因为它仍然会报告只有一位与本·阿弗莱克或彼得·杰克逊相匹配的导演的出版商。
with production as
(
select *
from (values
('DC', 'Batman', 'Ben Affleck'),
('DC', 'Robin', 'Peter Jackson'),
('Not DC', 'Not Batman', 'Not Ben Affleck'),
('Not DC', 'Not Robin', 'Not Peter Jackson'),
('Marvel', 'Avengers', 'Joe Russo'),
('WingNut', 'King Kong', 'Peter Jackson'),
('Century Fox', 'Deadpool', 'Ben Affleck'),
('Century Fox', 'Fantastic 4', 'Peter Jackson'),
('Century Fox', 'X-Men', 'Peter Jackson'),
('Millenium Fox', 'Scorpion', 'Ben Affleck'),
('Millenium Fox', 'Sub-Zero', 'Peter Jackson'),
('Millenium Fox', 'Liu Kang', 'Ed Boon')
) as x(publisher, movie, director)
)
select distinct P.publisher
from production P
where P.publisher not in (
-- Get publishers that have produced a movie directed by someone else
select P1.publisher
from production P1
where P1.director not in ('Ben Affleck', 'Peter Jackson')
)
;
错误的输出。WingNut 不应该被包括在内,因为它没有 Ben Affleck 和 Peter Jackson 作为导演。
| publisher |
| ----------- |
| WingNut |
| Century Fox |
| DC |
这是正确的查询,每个都是使用模拟的min(when true then 1 else 0) = 1
with production as
(
select *
from (values
('DC', 'Batman', 'Ben Affleck'),
('DC', 'Robin', 'Peter Jackson'),
('Not DC', 'Not Batman', 'Not Ben Affleck'),
('Not DC', 'Not Robin', 'Not Peter Jackson'),
('Marvel', 'Avengers', 'Joe Russo'),
('WingNut', 'King Kong', 'Peter Jackson'),
('Century Fox', 'Deadpool', 'Ben Affleck'),
('Century Fox', 'Fantastic 4', 'Peter Jackson'),
('Century Fox', 'X-Men', 'Peter Jackson'),
('Millenium Fox', 'Scorpion', 'Ben Affleck'),
('Millenium Fox', 'Sub-Zero', 'Peter Jackson'),
('Millenium Fox', 'Liu Kang', 'Ed Boon')
) as x(publisher, movie, director)
)
select P.publisher
from (select distinct publisher, director from production) P
group by
P.publisher
having
count(p.Director) = 2 -- The directors should be exactly 2
and min(case when p.Director in ('Ben Affleck', 'Peter Jackson')
then 1 else 0 end) = 1
;
正确的输出,应该只显示 DC 和 Century Fox。因为他们是唯一同时雇佣本·阿弗莱克和彼得·杰克逊的出版商。
| publisher |
| ----------- |
| Century Fox |
| DC |
现场测试:https ://www.db-fiddle.com/f/aDDw4Pd1DJzs6J5HgbKbdh/4