我目前正忙着做家庭作业......
我们正在使用sakila db(https://dev.mysql.com/doc/sakila/en/)
练习是找到并选择每部影片,其中不止一个演员具有相同的名字并选择这些演员
e.g。
title vn nn
AFRICAN EGG MATTHEW TAUTOU
AFRICAN EGG MATTHEW LEIGH
ANALYZE HOOSIERS TOM MCKELLEN
ANALYZE HOOSIERS TOM MIRANDA
我目前使用3个表格(表格 - > https://dev.mysql.com/doc/sakila/en/sakila-structure-tables.html):
我目前正在选择一部电影中的每个演员,这部电影中有超过1名具有相同名字的演员:
SELECT f.title title, a.actor_id, a.first_name vn, a.last_name nn FROM film_actor fa
LEFT JOIN actor a ON a.actor_id = fa.actor_id
LEFT JOIN film f ON f.film_id = fa.film_id
WHERE fa.film_id IN
(
SELECT fa.film_id FROM film_actor fa
LEFT JOIN actor a ON a.actor_id = fa.actor_id
LEFT JOIN film f ON f.film_id = fa.film_id
GROUP BY a.first_name, f.title HAVING count(a.first_name) > 1
)
ORDER BY title;
我得到了这个结果:
title actor_id vn nn
DESPERATE TRAINSPOTTING 117 RENEE TRACY
DESPERATE TRAINSPOTTING 137 MORGAN WILLIAMS
DESPERATE TRAINSPOTTING 187 RENEE BALL
DESPERATE TRAINSPOTTING 77 CARY MCCONAUGHEY
我不知道如何只获取重复演员的名字...... 有什么建议吗?
答案 0 :(得分:0)
使用COUNT(DISTINCT firstname)
:
SELECT f.title title, a.actor_id, a.first_name vn, a.last_name nn
FROM film_actor fa
LEFT JOIN actor a
ON a.actor_id = fa.actor_id
LEFT JOIN film f
ON f.film_id = fa.film_id
INNER JOIN
(
SELECT a.first_name, fa.film_id
FROM film_actor fa
LEFT JOIN actor a
ON a.actor_id = fa.actor_id
WHERE fa.film_id IN
(
SELECT fa.film_id
FROM film_actor fa
LEFT JOIN actor a
ON a.actor_id = fa.actor_id
LEFT JOIN film f
ON f.film_id = fa.film_id
GROUP BY fa.film_id
HAVING COUNT(DISTINCT a.first_name) > 1
)
GROUP BY a.first_name, fa.film_id
HAVING COUNT(*) > 1
) t
ON a.first_name = t.first_name AND
fa.film_id = t.film_id
在您的原始尝试中,您正在检查所有名字的数量。当然,对于任何拥有多个演员的电影来说,这都是正确的。相反,你想要检查不同演员的数量。