我有4个表,如下所示,具有以下属性:
Actor:actor_id,firstname,lastname
film_actor:actor_id,film_id
film_category:film_id,category_id
category:category_id,name
我想找到所有在电影中工作的演员的名单,他们的电影id,类别id和类别名称。
我想用In子句进行foll查询。因此,我通过如下实现获得o/p:
select a.first_name,a.actor_id,fc.film_id,c.name,c.category_id
from actor a,film_actor fa,film_category fc,category c where a.actor_id
in (select fa.film_id from film_actor fa where fa.actor_id=a.actor_id
and fa.film_id
in (select fc.film_id from film_category fc where fc.film_id=fa.film_id
and fc.category_id
in(select fc.category_id from category c where c.category_id=fc.category_id)))
但是假设现在我想知道特定类别的演员列表
它就在眼前。所以我做了如下修改:
select a.first_name,a.actor_id,fc.film_id,c.name,c.category_id
from actor a,film_actor fa,film_category fc,category c
where a.actor_id in
(select fa.film_id from film_actor fa where fa.actor_id=a.actor_id
and fa.film_id
in (select fc.film_id from film_category fc where fc.film_id=fa.film_id
and fc.category_id
in(select fc.category_id from category c where c.category_id=fc.category_id
and category_id=5)))
我得到的结果是空的。最后,我们什么时候应该使用IN子句,什么时候不应该?
最佳答案
不要用IN
来做这个。。改为使用JOIN
。
select
a.first_name,
a.actor_id,
fc.film_id,
c.name,
c.category_id
from
actor a join
film_actor fa on fa.actor_id = a.actor_id join
film_category fc on fc.film_id = fa.film_id join
category c on c.category_id = fc.category_id and c.category_id = 5
我通常只对一组硬编码的id使用
IN
。。。JOIN
或EXISTS
其他情况。这不仅更干净,而且可能会导致更好的执行计划。