在三个表中:
Actors:
+------------------+
| id_a | actor_name|
+------------------+
| 1 | AAA |
| 2 | Bbb |
| 3 | Ccc |
| 4 | Ddd |
| 5 | Eee |
+------------------+
Movies:
+----------------+
| id_m | mov_name|
+----------------+
| 1 | LoR |
| 2 | Thron |
| 3 | ZsT |
+----------------+
actors_in_movies:
+-------------+
| id_m | id_a |
+-------------+
| 1 | 1 |
| 1 | 3 |
| 1 | 5 |
| 2 | 1 |
| 2 | 3 |
| 3 | 2 |
| 3 | 3 |
| 3 | 4 |
| 3 | 5 |
+-------------+
可以编写一个查询来获取:所有来自查询的演员的电影吗?
示例:SELECT id_m WHERE id_a IN(1,3,4,5),应该给出:
+------+
| id_m |
+------+
| 1 |
| 2 |
+------+
然而.. SELECT id_m WHERE id_a IN(1,9)应该给出NULL。
我尝试了类似的查询:Finding ID having all values (mySQL, SQL),写了类似的内容:
SELECT id_m, count(*), group_concat(id_a) as all_act
FROM actors_in_movies
WHERE
id_m IN (SELECT id_m FROM actors_in_movies WHERE id_a = 1)
AND
id_m IN (SELECT id_m FROM actors_in_movies WHERE id_a = 3)
AND
id_m IN (SELECT id_m FROM actors_in_movies WHERE id_a = 5)
GROUP BY (id_m)
HAVING count(*) <= 3
它只显示一部电影(id_m:1), 如果我使用'或'它几乎可以, 但是对我来说重要的是让所有电影都来自查询演员, 演员或更少的演员,从来没有演员错过查询的电影。 怎么写?
答案 0 :(得分:0)
使用group by
和having
:
SELECT id_m
FROM table
WHERE id_a IN (1, 9)
GROUP BY id_m
HAVING COUNT(DISTINCT id_a) = 2;