MySQL选择上一个语句的结果

时间:2012-12-22 13:52:59

标签: mysql sql

我对SQL很陌生我遇到了这个问题: 我有人有权力的关系表

A has X
A has Z
B has X
B has Y
C has Y
D has Z

我想选择所有具有X和Y权力的人,在这种情况下是B.当然,我将拥有更复杂的权力组合。

2 个答案:

答案 0 :(得分:1)

做这样的事,

SELECT person
FROM tableName
WHERE power IN ('x', 'y')
GROUP BY Person
HAVING COUNT(*) = 2

如果对每个人的power强制执行唯一约束,则需要使用DISTINCT

SELECT person
FROM tableName
WHERE power IN ('x', 'y')
GROUP BY Person
HAVING COUNT(DISTINCT power) = 2

答案 1 :(得分:1)

这称为relational division,这是执行此操作的一种方法:

SELECT person
FROM Powers
WHERE power IN ('x', 'y')
GROUP BY person
HAVING COUNT(power) = 2