提供这种数据库结构如何编写查询以仅查找同时拥有男性和女性顾客的电影?
movie
movID
name
ticket
TID
movID
patronID
patron
PID
gender
答案 0 :(得分:2)
然后说要做两个问题以获得所有男性顾客和女性顾客,然后加入基于movIE的那些:
WITH malePatrons AS
(
SELECT name, m.movID
FROM movie JOIN ticket tic ON movie.movID = tic.movID
JOIN patron pat ON pat.PID = tic.patronID
WHERE pat.gender = "male"
), femalePatrons AS
(
SELECT name, m.movID
FROM movie JOIN ticket tic ON movie.movID = tic.movID
JOIN patron pat ON pat.PID = tic.patronID
WHERE pat.gender = "female"
)
Select * FROM malePatrons JOIN femalePatrons fem ON malePatrons.movID = fem.movID
答案 1 :(得分:0)
您不需要多次查询表。我的评论可能过于晦涩,但我试图暗示你这样的事情:
select m.name
from movie m
join ticket t on t.movid = m.movid
join patron p on p.pid = t.patronid
group by m.movid, m.name
having count(distinct p.gender) = 2;
这将查找所有电影的所有门票,并计算拥有这些门票的赞助人的不同性别的数量。 (这假设当然只有两种性别,为简单起见;如果你有更多,那么你可以添加一个过滤器)。 having
子句检查计数是2.如果电影只有男性或女性顾客,而不是两者,则计数将为1,并且将从结果中排除。
答案 2 :(得分:0)
Select m.movieid, name, count(distinct(gender))as Count
from
MOVIE m
JOIN
Ticket t
on m.movid=t.movid
JOIN
patron P
on
t.patronid=p.Pid
GROUP BY m.movieid, name
HAVING count(distinct(gender)) > 1