我整天都在思考这个问题,我似乎无法想出一个解决方案。让我们举一个例子,我有一个看起来像这样的表:
| movies | personname | personrole |
-------------------------------------
| A | p1 | director |
| A | p1 | producer |
| A | p1 | writer |
| A | p1 | actor |
| A | p2 | actor |
| A | p3 | writer |
| A | p3 | producer |
| B | p4 | director |
| B | p4 | producer |
| B | p4 | writer |
现在,我要做的是列出此表中是导演,制作人和电影作家的所有人。任何帮助表示赞赏!
This as output:
| movies | personname |
-----------------------
| A | p1 |
| B | p4 |
答案 0 :(得分:2)
此问题称为SQL of Relational Division。
SELECT movies,
personName
FROM tableName
WHERE personrole IN ('director','producer','writer')
GROUP BY movies, personName
HAVING COUNT(*) = 3
如果personrole
对于每个movies
和personname
都不是唯一的,则需要使用DISTINCT
来计算唯一值
SELECT movies,
personName
FROM tableName
WHERE personrole IN ('director','producer','writer')
GROUP BY movies, personName
HAVING COUNT(DISTINCT personrole) = 3