如何根据表中的特定条件选择表中的特定行?

时间:2013-09-21 11:43:06

标签: mysql sql

我整天都在思考这个问题,我似乎无法想出一个解决方案。让我们举一个例子,我有一个看起来像这样的表:

| 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         |  

1 个答案:

答案 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对于每个moviespersonname都不是唯一的,则需要使用DISTINCT来计算唯一值

SELECT  movies,
        personName
FROM    tableName
WHERE   personrole IN ('director','producer','writer')
GROUP   BY movies, personName
HAVING  COUNT(DISTINCT personrole) = 3