查询数据库以查找与关系表相交的记录列表

时间:2013-10-27 00:58:21

标签: sql sql-server-2008 where

我试图查找包含2个或 MORE 演员的所有电影的列表。

select title from Movie where movieID in(
    select movieID
    from Cast
    join MovieHasCast
        on Cast.castID = MovieHasCast.castID
    where cast.name = 'gene wilder'
intersect
    select movieID
    from Cast
    join MovieHasCast
        on Cast.castID = MovieHasCast.castID
    where cast.name = 'richard pryor')

我的替代方案是这样的:

select title from Movie where movieID in(
    select movieID
    from Cast
    join MovieHasCast
        on Cast.castID = MovieHasCast.castID
    where cast.name = 'gene wilder'
    and movieID in (
        select movieID
        from Cast
        join MovieHasCast
            on Cast.castID = MovieHasCast.castID
        where cast.name = 'richard pryor'))

这只是我如何实现这一目标的一个例子。但是,我正在C#中动态构建此查询,以按流派,演员等过滤电影列表。我关注的是性能。

这是完成此任务的最佳方法吗?我觉得有更好的方法可以做到这一点我只是不知道怎么特别是因为用户可以选择10个演员和该查询会开始变得非常大 - 即使它可能会返回0条记录。

1 个答案:

答案 0 :(得分:1)

尝试

select movie.name
from movie
join moviehascast mc on mc.movieid = movie.id
join cast on cast.id = mc.castid
where cast.name in (@actor1, @actor2)
group by movie.name
having count(1) = @numberOfActorsSearched