简体   繁体   English

SQL:选择子查询的总和

[英]SQL: Select the sum of a subquery

I have a few related tables containing film, actor, and category data. 我有一些相关的表格,其中包含电影,演员和类别数据。 I am trying to sum the length of the films in a particular category for each actor. 我试图总结每个演员在特定类别中的电影长度。

Here's what I have to try and include the sum of a category ID subquery in my results: 这是我必须尝试在结果中包括类别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

However my total column just contains all NULL values. 但是,我的total列仅包含所有NULL值。

This query works, but does not include actors who have 0 minutes worth of films in this category: 此查询有效,但不包括该类别中有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

You need an outer join and the criteria on category belongs in the on clause of the outer join: 您需要一个外部联接,并且类别上的条件属于外部联接的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

In your first query you're adding up the lengths of all category 14 films regardless of actor, hence you'll see the same value for each actor. 在第一个查询中,您将累加所有14类电影的长度,与演员无关,因此您将为每个演员看到相同的值。 If the values are all null then you have no films in category 14. 如果所有值均为空,则类别14中没有电影。

I suspect you want to add up the length of category 14 films for each actor.... 我怀疑您想为每个演员加起来14类电影的长度....

SELECT actor.actor_id, SUM(IFNULL(film.length, 0))
FROM actor 
JOIN film_actor USING(actor_id)
JOIN film USING(film_id)
LEFT JOIN film_category 
   ON film_category.film_id=film.film_id
   AND film_category.category_id=14
GROUP BY actor.actor_id

Here's how I got to what I needed: 这是我所需要的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM