SQL - 演员之间的关系

时间:2013-10-02 12:14:31

标签: mysql sql

我有一个包含2列的单个表:演员和电影,如下所示:

ACTOR  | MOVIE
-------+-------------
Volta  | Pulp Fiction
Bruce  | Pulp Fiction
Rhame  | Pulp Fiction
Walke  | Pulp Fiction
Rhame  | Bad Movie
Bruce  | Bad Movie
Volta  | Decent Movie
Brian  | Decent Movie
Walke  | Awesome Movie
Brian  | Awesome Movie

我想知道哪些演员出现在低俗小说中,从未出现在与另一位来自制浆小说的演员的另一部电影中。

从这个例子中,输出应该是:

Volta
Walke

因为他们分别出现在低俗小说,体面电影和令人敬畏的电影中,没有任何其他来自制浆小说的演员。

我正在使用MySQL。

4 个答案:

答案 0 :(得分:2)

SELECT m.actor
FROM movies m 
WHERE 
m.movie = 'Pulp Fiction'
AND NOT EXISTS
(
  SELECT 1
  FROM movies m1 
    JOIN movies m2 ON m1.movie = m2.movie 
      AND m1.actor <> m2.actor 
      AND m2.movie <> 'Pulp Fiction' 
      AND m2.actor IN (SELECT actor FROM movies WHERE movie = 'Pulp Fiction')
  WHERE
      m.actor = m1.actor 
)

根据ChrisProsser所做的SQLFiddle,它应该给出正确的结果。

答案 1 :(得分:0)

可能有一种更简单的方法,但这应该有效:

select m.actor 
  from movies m
 where m.movie = 'Pulp Fiction'
   and m.actor not in (
       select m2.actor
         from movies m1,
              movies m2,
              movies m3
        where m1.actor = m2.actor
          and m1.movie = 'Pulp Fiction'
          and m2.movie != m1.movie
          and m3.movie = m2.movie
          and m3.actor in (select m4.actor
                             from movies m4
                            where m4.movie = 'Pulp Fiction')
        group by m2.actor
        having count(*) > 1);

我创建了一个SQL Fiddle来测试它,输出是正确的。

答案 2 :(得分:0)

试试这个......

SELECT actor, movie 
FROM actor
where movie like 'Pulp Fiction' AND
movie NOT IN(select movie from tablename t where t.actor like actor and movie NOT LIKE 'Pulp Fiction');

答案 3 :(得分:-1)

SELECT actor FROM table AS t1  
WHERE movie = 'Pulp Fiction' AND  
NOT EXISTS( 
  SELECT 1 FROM table AS t2 WHERE t2.actor = t1.actor AND movie <> 'Pulp Fiction' 
) 

我建议您将电影和演员存储在不同的表格中(“电影”表和“演员表”),然后使用“movie_actor”表将数据相互连接。