使用JOIN的SQL查询

时间:2011-04-20 08:44:40

标签: sql

我有这张桌子

Movie a
id  title           yr    score  votes
--  --------------  ----  -----  -----
1   ‘Harry Potter’  1985  9.98   2
2   ‘Beasdas’       1985  5.28   3

actor b
id  name
--  --------------
1   ‘Keanu Reeves’

casting c
movieid  actorid  ord
-------  -------  ---
1        1        2

我想列出所有'朱莉安德鲁斯'电影的电影片名和主角。 这是对的吗?

SELECT title, name
   FROM movie a, actor b, casting c
   WHERE title IN(SELECT title
                  FROM movie a, actor b, casting c
                  WHERE name = 'Julie Andrews' AND
                             a.id = c.movieid  AND
                             b.id = c.actorid) AND
                                         ord = '1' AND
                                         a.id = c.movieid AND
                                         b.id = c.actorid;    

3 个答案:

答案 0 :(得分:2)

如果你想要笛卡儿产品 它看起来像这样

SELECT title, name   
FROM movie a, actor b, casting c  
 WHERE --conditions for joining ables   
   a.id = c.movieid  AND    
b.id = c.actorid and
--other conditions    
  b.name = 'Julie Andrews' 
AND    b.ord = '1' 

但加入更好

select title, name
FROM movie a
  join casting c on a.id = c.movieid
  join actor b   on b.id = c.actorid
where b.name = 'Julie Andrews' AND
  b.ord = '1'

答案 1 :(得分:2)

如果你想要所有结果'朱莉安德鲁斯'是主演,那么这就是你需要的:

SELECT a.Name, m.Name
FROM Actor a
INNER JOIN Casting AS c ON a.actorid = a.id AND c.ord = 1
INNER JOIN Movie AS m ON m.id = c.movieid
WHERE a.name = 'Julie Andrews'

另一方面,如果你需要所有'Julie Andrews'扮演角色的电影,但不一定是主演,那么你需要以下内容:

SELECT m.Title, a2.Name 
FROM Movie AS m
INNER JOIN Casting AS c1 ON c1.movieid = m.id
INNER JOIN Actor AS a1 ON a1.id = c1.actorid AND a1.name = 'Julie Andrews'
INNER JOIN Casting AS c2 ON c2.movieid = m.id AND c2.ord = 1 
INNER JOIN Actor AS a2 ON a2.id = c2.actorid

希望这有帮助!

答案 2 :(得分:1)

你能写下预期的结果吗? 似乎有三个表

1.Movie 2.Actor 3.Casting Casting是一个连接表,其中包含Movie和Actor的组合信息。