让在每种电影类别中都曾扮演过至少两次的所有演员(Sakila DB)

时间:2018-11-25 12:10:00

标签: sql

我正在Sakila DB上运行查询,我希望让在每个电影类别中都曾扮演过至少两次的所有演员。

我无法在查询中实现至少两次的条件,因此,我对此表示感谢。

我的尝试:

SELECT DISTINCT first_name, last_name
FROM actor, film_category, film_actor
WHERE actor.actor_id=film_actor.actor_id AND 
film_actor.film_id=film_category.film_id 
   AND EXISTS(SELECT NULL 
              FROM film_category
              WHERE film_actor.film_id=film_category.film_id 
              )
HAVING COUNT(film_category.film_id)>1
ORDER BY first_name, last_name

2 个答案:

答案 0 :(得分:1)

从不FROM子句中使用逗号。 始终使用正确的,明确的标准JOIN语法。

这是一个复杂的查询。它首先计算每个演员/类别的电影数量。 。 。然后确保至少有两个并且所有类别都被覆盖。

第一部分是:

select fa.actor_id, fc.category_id, count(*) as num_films
from film_actor fa join
     film_category fc
     on fa.film_id = fc.film_id
group by fa.actor_id, fc.category_id; 

接下来,我们将通过对该查询和having子句进行汇总,为“至少两部电影”和“所有类别”添加条件:

select actor_id
from (select fa.actor_id, fc.category_id, count(*) as num_films
      from film_actor fa join
           film_category fc
           on fa.film_id = fc.film_id
      group by fa.actor_id, fc.category_id
     ) ac
group by actor_id 
having min(num_films) >= 2 and
       count(*) = (select count(*) from category)

答案 1 :(得分:0)

使用显式连接并使用内部查询

SELECT DISTINCT first_name, last_name
FROM actor a join film_actor fa
on a.actor_id=fa.actor_id
join film_category fc on  fa.film_id=fc.film_id     
WHERE      
   EXISTS (SELECT NULL 
              FROM film_category t1 join film_actor fa1
              on fa1.film_id=t1.film_id                      
              WHERE fa.actor_id=fa1.actor_id
              group by fa1.actor_id,t1.category_id
              HAVING COUNT( distinct film_category.film_id)>1
              )

ORDER BY first_name, last_name