连接表中的选定语句

时间:2014-03-31 10:00:18

标签: sql sql-server

movie

   id ,title,yr,director,budget,gross

actor

   id,name

casting

   movieid,actorid,ord

我有一个问题,我一直在询问(与所有1962年电影的主要明星一起列出电影。)[注意:演员的ord领域给出了演员的位置。如果ord = 1,那么这个角色扮演主角]

我的回答是:

select 
    title, name 
from 
    movie 
join 
    casting on movie.id = casting.movieid
join 
    actor on actor.id = casting.actorid
where 
    yr = 1962 and movie.id = casting.movieid and actor.id = casting.actorid and casting.ord = 1  
group by 
    title

但是我的问题是我可以接近答案,我在ord部分遇到问题,因为有些演员没有1只为演员只显示两个,所以它不会显示在输出上。

我怎样才能选择ord = 1或ord = 2(但不是两者)(和1具有更高的优先级)

希望任何人都可以帮助我。

4 个答案:

答案 0 :(得分:0)

将CROSS APPLY(http://technet.microsoft.com/en-us/library/ms175156(v=sql.105).aspx)与由“ord'”排序的子查询一起使用。列,并有一个TOP(1)条款。

SELECT
    M.title
    , CA.name 
FROM
    movie AS M
    CROSS APPLY (
        SELECT TOP(1)
            actor.name
        FROM
            casting C
            INNER JOIN actor A
                ON C.actorid = A.id
        WHERE
            M.id = C.movieid
        ORDER BY
            ord
        ASC
) AS CA

答案 1 :(得分:0)

select title,coalesce (c.name,c21.name) as actorname from movie m 
left join (select * from casting where ord=1) c on m.id= c.movieid
left join (select * from casting where ord=2) c1 on c.movieid = c1.movieid 
left join actor a on a.id= c.actorid
where yr=1962

答案 2 :(得分:0)

希望这会输出您的预期结果

   Select title,name
    From Movie M
       Cross Apply (Select  top 1 movieid,actorid,ord from  Casting Order By ord) as Cast
    Inner join Actor A On A.id = Cast. actorid

答案 3 :(得分:0)

我有2个答案:

SELECT movie.title, (select actor.name from actor where actor.id = casting.actorid)
FROM movie
JOIN casting
ON movie.id =casting.movieid
WHERE movie.yr = 1962 and casting.ord = 1

然后我意识到你可以链接:

SELECT movie.title, actor.name
FROM movie
JOIN casting ON movie.id=casting.movieid
JOIN actor ON casting.actorid = actor.id
WHERE movie.yr = 1962 and casting.ord = 1

第二个显然要简单得多。 (不需要嵌套SELECT语句。

要让它选择或,请执行... and (casting.ord = 1 xor casting.ord = 2)。 要按1排序,请尝试Order by casting.ord in (1,2)之类的内容。 (我没有测试过。