简体   繁体   中英

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:

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.

This query works, but does not include actors who have 0 minutes worth of films in this category:

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:

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. If the values are all null then you have no films in category 14.

I suspect you want to add up the length of category 14 films for each actor....

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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