您好,我目前正在处理SQL问题,我无法理解。以下是我使用的Schema:
以下是我坚持的问题:
- 3找到每个演员的科幻电影的名字,姓氏和总电影长度。这就是结果应该列出所有演员的名字(即使一个演员没有参演任何科幻电影)以及他们所在的科幻电影的总长度。
到目前为止我已经
了SELECT actor.first_name, actor.last_name, (SELECT SUM(film.length)
from film
INNER JOIN film_category
ON film.film_id = film_category.film_id
INNER JOIN category
ON film_category.category_id = category.category_id
INNER JOIN film_actor
ON film_actor.film_id = film.film_id
INNER JOIN actor
ON film_actor.actor_id = actor.actor_id
WHERE category.name = 'Sci-fi'
)
from actor
我知道我需要通过actor_id对其进行分组,但我无法在select子查询中执行此操作。有人有提示吗?
答案 0 :(得分:4)
无需使用子查询。聚合函数适用于整个数据集。 'group by'指定如何对您正在聚合的数据进行分组。
select a.actor_id, a.first_name, a.last_name, sum(f.length)
from actor a
left outer join film_actor fa on fa.actor_id = a.actor_id
left outer join film f on f.film_id = fa.film_id
left outer join film_categories fc on fc.film_id = f.film_id
left outer join categories c on c.category_id = fc.category_id
where c.name = 'sci-fi'
group by a.actor_id
;
外部联接确保没有科幻电影经验的演员被
包括在结果中答案 1 :(得分:1)
我不明白你需要什么子查询,试试这个:
SELECT actor.first_name, actor.last_name,SUM(film.length)
from film
INNER JOIN film_category
ON film.film_id = film_category.film_id
INNER JOIN category
ON film_category.category_id = category.category_id
INNER JOIN film_actor
ON film_actor.film_id = film.film_id
INNER JOIN actor
ON film_actor.actor_id = actor.actor_id
WHERE category.name = 'Sci-fi'
GROUP BY actor.actor_id;
答案 2 :(得分:1)
这应该可以让你得到你想要的东西,包括有关在科幻电影中没有演员的部分。您可以在电影中左键加入以包含film_actor所在的所有电影。附加的AND语句与LEFT JOIN一起使用,以包括不在Sci-Fi电影中的演员为您的总和功能。
SELECT a.actor_id, a.first_name, a.last_name, sum(f.length) AS length
FROM actor a
INNER JOIN film_actor fa ON fa.actor_id = a.actor_id
INNER JOIN film_category fc ON fc.film_id = fa.film_id
INNER JOIN category c ON c.category_id = fc.category_id
LEFT JOIN film f ON f.film_id = fa.film_id
AND c.name = 'Sci-Fi'
GROUP BY a.actor_id;
答案 3 :(得分:0)
这里的最佳答案实际上并不正确。这将有效:
SELECT T1.first_name, T1.last_name, T2.total
FROM
(SELECT a.first_name, a.last_name, a.actor_id
FROM actor a
)
AS T1
LEFT JOIN
(SELECT a.first_name, a.last_name, a.actor_id, SUM( f.length ) AS total, c.name
FROM actor a, film_actor fa, film f, film_category fc, category c
WHERE c.category_id = fc.category_id
AND fc.film_id = f.film_id
AND a.actor_id = fa.actor_id
AND fa.film_id = f.film_id
AND c.name = 'sci-fi'
GROUP BY a.actor_id)
AS T2
ON T1.actor_id = T2.actor_id;
它需要所有演员,并将它们与科幻演员结合起来,为所有人提供科幻电影的合并屏幕时间。在你的数据集上测试它,为我工作。