我有三个表:一个演员列表(actors.sql),一个电影列表(movies.sql),以及每个电影中扮演演员的列表(以及他们的角色,roles.sql)。以下是每个表格的摘要:
这些表格长得多,此图片中未显示数千个条目。我之前的实践问题是显示演员出现的每部电影的表格(从HTML表格中检索演员名称,在另一页面上搜索PHP)。其代码如下:
SELECT actor_id, movie_id, name, year
FROM roles r
JOIN actors a ON a.id = r.actor_id
JOIN movies m ON m.id = r.movie_id
WHERE first_name = '$actor_first' AND last_name = '$actor_last'
ORDER BY year DESC;
现在我想交叉引用表格,找出谁与特定演员合作以及他们合作过的电影。说我想看看哪些电影“凯文斯派西”出现在“威尔史密斯”中,我想要一张列出它们的表格。问题是,我不确定如何。
任何提示?
答案 0 :(得分:2)
如果您有两个演员,则可以使用此查询
select m.*
from movies m
where exists (select 1
from roles r1
inner join actors a1
on a1.actor_id = r1.actor_id
where r1.movie_id = m.movie_id
and a1.first_name = 'Kevin'
and a1.last_name = 'Spacey')
and exists (select 1
from roles r2
inner join actors a2
on a2.actor_id = r2.actor_id
where r2.movie_id = m.movie_id
and a2.first_name = 'Will'
and a2.last_name = 'Smith')
它将返回两个演员都扮演角色的所有电影的所有电影数据。
答案 1 :(得分:1)
除了接受的答案之外,您可以这样做,计算结果中movie_ID
的记录数,并且等于您在条件中提供的演员数。
SELECT m.*
FROM movies m
INNER JOIN
(
SELECT a.movie_ID
FROM roles a
INNER JOIN actors b
ON a.actor_ID = b.id
WHERE (b.first_name = 'Kevin' AND b.last_name = 'Spacey') OR
(b.first_name = 'Will' AND b.last_name = 'Smith')
GROUP BY a.movie_ID
HAVING COUNT(*) = 2
) n ON m.movie_ID = n.movie_ID
查询发生了什么?
WHERE (b.first_name = 'Kevin' AND b.last_name = 'Spacey') OR
(b.first_name = 'Will' AND b.last_name = 'Smith')
通过添加OR
条件运算符
HAVING COUNT(*) = 2
COUNT
的值应该等于您要搜索的演员数量。
如果你需要找到3个在同一部电影上合作的演员,那么你应该只修改WHERE
子句和HAVING
子句的值。
WHERE (b.first_name = 'Kevin' AND b.last_name = 'Spacey') OR
(b.first_name = 'Will' AND b.last_name = 'Smith') OR
(b.first_name = 'Ben' AND b.last_name = 'Affleck')
GROUP BY a.movie_ID
HAVING COUNT(*) = 3