我有一个查询可以完成这个,但它排除了从未参加过科幻电影的演员。我想包括那些演员,即使科幻片的总长度为零。
结果应该列出所有演员的名字(即使演员没有参演任何科幻电影)以及他们所在科幻电影的总长度。
我有以下查询,我只是不知道如何修改它以包含所有演员。
SELECT actor.first_name, actor.last_name, SUM(film.length)
FROM actor
INNER JOIN film_actor ON actor.actor_id = film_actor.actor_id
INNER JOIN film on film_actor.film_id = film.film_id
INNER JOIN film_category ON film_actor.film_id = film_category.film_id
INNER JOIN category ON film_category.category_id = category.category_id
WHERE category.name = 'Sci-Fi'
GROUP BY category.name, actor.actor_id
ORDER BY actor.first_name
我正在使用以下架构:
答案 0 :(得分:2)
除了切换到外部联接之外,您还可以使用条件聚合(可以轻松扩展到包括其他类别):
SELECT actor.first_name, actor.last_name,
SUM(case when category.name = 'Sci-Fi' then film.length else 0 end)
FROM actor
INNER JOIN film_actor ON actor.actor_id = film_actor.actor_id
INNER JOIN film on film_actor.film_id = film.film_id
INNER JOIN film_category ON film_actor.film_id = film_category.film_id
INNER JOIN category ON film_category.category_id = category.category_id
GROUP BY category.name, actor.actor_id
ORDER BY actor.first_name
这将排除那些从未制作过电影的演员。
答案 1 :(得分:1)
您应该更改连接顺序并使用右连接与actor表而不是内连接:
SELECT actor.first_name, actor.last_name, SUM(film.length)
FROM category
INNER JOIN film_category ON film_category.category_id = category.category_id and category.name = 'Sci-Fi'
INNER JOIN film on film.film_id = film_category.film_id
INNER JOIN film_actor ON film.film_id = film_actor.film_id
RIGHT JOIN actor ON actor.actor_id = film_actor.actor_id
GROUP BY actor.first_name, actor.last_name
ORDER BY actor.first_name