我有以下表格:
电影:
+----------+--------------+
| movie_id | title |
+----------+--------------+
| 1 | Wonder Woman |
+----------+--------------+
演员:
+----------+--------------+
| id | name |
+----------+--------------+
| 1 | Gal Gadot |
+----------+--------------+
| 2 | Chris Pine |
+----------+--------------+
Movie_cast:
+----------+--------------+--------------+
| id | movie_id | cast_id |
+----------+--------------+--------------+
| 1 | 1 | 1 |
+----------+--------------+--------------+
| 2 | 1 | 2 |
+----------+--------------+--------------+
基本上,Gal Gadot和Chris Pine都是电影“神奇女侠”的一部分。
我的问题是我想找到他们都的所有电影。我不希望任何电影分别播放,只有他们两个都在铸造。
我试过这样的事情:
SELECT * FROM movies
LEFT JOIN movie_cast ON movie_cast.movie_id = movies.movie_id
LEFT JOIN cast ON movie_cast.cast_id = cast.id
WHERE cast.id = 1 AND cast.id = 2
但结果是空的。
答案 0 :(得分:1)
你应该用这个:
SELECT m.movie_id, m.title
FROM movies m
INNER JOIN movie_cast mc ON mc.movie_id = m.movie_id
WHERE mc.cast_id = 1 OR mc.cast_id = 2
GROUP BY m.movie_id, m.title
HAVING COUNT(*) = 2; -- HAVING COUNT(DISTINCT mc.cast_id) = 2; -- for unnormalized data
无需LEFT JOIN,只需要通过演员姓名找到<{1}}表格
答案 1 :(得分:1)
您可以在FROM子句中使用子查询来缩小它们所在的电影的范围。通过将转换限制为只有它们的ID号并对其进行分组,任何具有Cast_Total为2的movie_id都将具有这两个个体主演。
SELECT m.title
FROM (SELECT movie_id, COUNT(cast_id) AS Cast_Total
FROM movie_cast
WHERE cast_id IN (1, 2)
GROUP BY movie_id) temp
LEFT JOIN movies m ON m.movie_id = temp.movie_id
WHERE temp.Cast_Total = 2
答案 2 :(得分:0)
自我加入Movie_cast以获得两位演员的电影,然后将其加入电影。
SELECT * FROM Movies A
INNER JOIN
(SELECT DISTINCT M1.movie_id movie_id FROM Movie_cast
M1 INNER JOIN Movie_cast M2 ON M1.movie_id = M2.movie_id
WHERE M1.cast_id = 1 AND M2.cast_id = 2) B
ON A.movie_id = B.movie_id
通用版,获取丢失演员的电影(说表A)。使用此套装A连接主要电影并过滤掉丢失演员阵容的电影。
SELECT * FROM Movies A
LEFT OUTER JOIN
(
SELECT DISTINCT movie_id movie_id
FROM Movie_cast M1 WHERE NOT EXISTS (SELECT 1 FROM Cast WHERE Id = M1.cast_id)
) B ON A.Id = B.movie_id
WHERE B.movie_id IS NULL