检索具有多个关联条目的行

时间:2013-07-05 15:02:23

标签: mysql sql

假设我有一个ASOC类型的表,其中包含以下条目:

+----------+----------+
| PERSON   | SKILL    |
+----------+----------+
| Bob      | Java     |
| Bob      | Database |
| Sarah    | Java     |
| Sarah    | HTML     |
| Jane     | Java     |
| Jane     | HTML     |
| Jane     | Database |
+----------+----------+

我想要一个查询,它将返回具有Java和数据库技能的人员列表,即Bob和Jane。

如果我运行如下查询:

SELECT PERSON
FROM   PERSON_SKILLS_ASOC
WHERE  SKILL = 'Java'
OR     SKILL = 'Database'

我也会得到莎拉,他没有资格获得我想填补的职位。我是否需要进行某种联合/交叉查询?

我在使用MySQL。提前谢谢。

4 个答案:

答案 0 :(得分:1)

select a.person
from (select person from person_skills_asoc where skill = 'Java') a
     (select person from person_skills_asoc where skill = 'Database') b
where a.person = b.person;

select a.person
from person_skills_asoc a, person_skills_asoc b
where a.person = b.person
  and a.skill = 'Java'
  and b.skill = 'Database';

答案 1 :(得分:0)

我多年没在MySQL工作了,所以我的语法可能略有不同,但要点是EXISTS

SELECT
    PSA1.Person
FROM
    PERSON_SKILLS_ASOC AS PSA1
WHERE
        PSA1.Skill = 'Java'
    AND EXISTS (SELECT * FROM PERSON_SKILLS_ASOC AS PSA2 WHERE PSA1.Person = PSA2.Person AND PSA2.Skill = 'Database')

您也可以通过加入来实现这一目标。

答案 2 :(得分:0)

在SQL Server中,您可以使用INTERSECT,显然这在MySQL中不可用(但是?)。使用自联接的可能解决方案(请查看 SQLFiddle ):

SELECT P1.PERSON
FROM   PERSON_SKILLS_ASOC AS P1
INNER JOIN PERSON_SKILLS_ASOC AS P2 ON P1.PERSON = P2.PERSON
WHERE  P1.SKILL = 'Java'
       AND P2.SKILL = 'Database';

关于MySQL中INTERSECT的替代方案,还有另一个很好的答案:https://stackoverflow.com/a/3201426/249353

答案 3 :(得分:0)

使用这样的连接: -

SELECT a.PERSON
FROM   PERSON_SKILLS_ASOC a
INNER JOIN PERSON_SKILLS_ASOC b ON a.PERSON = b.PERSON
WHERE  a.SKILL = 'Java'
AND    b.SKILL = 'Database'

或使用计数: -

SELECT PERSON
FROM   PERSON_SKILLS_ASOC a
WHERE  SKILL IN ('Java', 'Database')
GROUP BY PERSON
HAVING  COUNT(DISTINCT SKILL) = 2