MySQL查询单个表以查找多行

时间:2011-04-29 10:43:52

标签: mysql database

我正试图找出一种方法来查找电影数据库中两个人的共享信用,例如:

表:'学分' 列:'id','movie','person'

我的另一个问题是一个人可能有同一部电影的多个学分,所以如何过滤重复?任何帮助,将不胜感激。以下是我到目前为止的情况。我是在正确的轨道上吗?

SELECT DISTINCT movie
FROM credits
WHERE person = 'condition1' OR person = 'condition2'
GROUP BY movie
HAVING COUNT(*)=2

4 个答案:

答案 0 :(得分:1)

SELECT DISTINCT c1.movie
FROM credits AS c1
JOIN credits AS c2 on (c1.movie = c2.movie)
WHERE c1.person = 'john'
AND c2.person = 'kate'

答案 1 :(得分:1)

这应该有效:

SELECT DISTINCT movie
FROM (
      SELECT movie, COUNT(person) AS contributors
      FROM credits
      WHERE person IN('person1','person2')
      GROUP BY movie, person
      HAVING contributors>1
     ) t1

答案 2 :(得分:0)

select distinct cr1.movie
from credits as cr1
join credits as cr2
using (movie)
where cr1.person = {person 1 goes here}
and cr2.person = {person 2 goes here}

答案 3 :(得分:-1)

你不需要这个HAVING COUNT(*)=2。它只为您提供两场比赛的电影(一个人有两个学分,或同时有condition1condition2)。更重要的是 - 当您使用group by时(在这种情况下),您根本不需要distinct

SELECT DISTINCT movie
FROM credits
WHERE person = 'condition1' OR person = 'condition2'