0

假设我有一个 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

4 回答 4

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';
于 2013-07-05T15:06:08.007 回答
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')

您也可以通过加入来实现此目的。

于 2013-07-05T15:06:07.380 回答
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';

INTERSECT关于这里的 MySQL替代方案的 SO,还有另一个不错的答案: https ://stackoverflow.com/a/3201426/249353 。

于 2013-07-05T15:29:29.803 回答
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
于 2013-07-05T15:33:01.523 回答