SQL:选择子查询的总和

时间:2015-07-11 21:12:36

标签: mysql sql sum subquery aggregate-functions

我有一些包含电影,演员和类别数据的相关表格。我试图将每个演员的特定类别的电影长度加以总结。

以下是我必须尝试的内容,并在结果中包含类别ID子查询的总和:

SELECT actor.actor_id, (SELECT SUM(length) from film WHERE category_id=14) total
FROM actor
JOIN film_actor USING(actor_id)
JOIN film USING(film_id)
JOIN film_category USING(film_id)
JOIN category USING(category_id)
GROUP BY actor.actor_id
ORDER BY total DESC

但是我的total列只包含所有NULL值。

此查询有效,但不包括此类别中有0分钟影片的演员:

SELECT actor.actor_id, SUM(film.length) as total
FROM actor
JOIN film_actor USING(actor_id)
JOIN film USING(film_id)
JOIN film_category USING(film_id)
JOIN category USING(category_id)
WHERE category_id = 14
GROUP BY actor.actor_id

3 个答案:

答案 0 :(得分:0)

您需要外部联接,类别上的条件属于外部联接的on子句:

select a.actor_id,
       sum(f.length) as total
  from actor a
  join film_actor fa
    on a.actor_id = fa.actor_id
  join film f
    on fa.film_id = f.film_id
  left join film_category fc
    on fc.film_id = f.film_id
   and fc.category_id = 14
 group by a.actor_id

答案 1 :(得分:0)

在你的第一个查询中,无论演员如何,你都会将所有14类电影的长度相加,因此每个演员都会看到相同的值。如果值全部为空,那么您在第14类中没有电影。

我怀疑你想为每位演员加上14类电影的长度......

indexer --all

答案 2 :(得分:0)

以下是我如何得到我需要的东西:

SELECT actor.actor_id, SUM(film.length) as total
FROM actor
JOIN film_actor USING(actor_id)
LEFT JOIN film on film_actor.film_id = film.film_id AND film.film_id IN  (SELECT film_id FROM film_category WHERE film_category.category_id = 14)
GROUP BY actor.actor_id