sql选择inclusive中的where列

bmvo0sr5  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(328)

我有两张table,人和技能。

Person:

    PersonID: AutoNumber
    PersonName: String

Skill:

    SkillID: AutoNumber
    SkillName: String

我有一个联接表:

PersonSkills

    PersonID: Number (FK to Person.PersonID)
    SkillID: Number  (FK to Skill.SkillID)

我在person表中有两行

PersonID   PersonName
1          Bob
2          John

技能表中有四行

SkillID    SkillName
1          English
2          French
3          Math
4          Science

联接表

PersonID     SkillID
1            1             (Bob - English)
1            3             (Bob - Math)
1            4             (Bob - Science)
2            2             (John - French)
2            3             (John - Science)

我想得到一份所有拥有英语、数学和科学技能的人的名单。标准选择

SELECT Person.PersonName, Skill.SkillName
FROM   Person left outer join PersonSkills on Person.PersonID = 
PersonSkills.PersonID left outer join on Skills on PersonSkills.SkillID = 
Skills.SkillID
where Skill.SkillName in ('English','Math','Science')

会找回鲍勃和约翰。
如果这三种技能都具备,我如何获得唯一的结果?

wn9m85ua

wn9m85ua1#

按人员汇总,然后声明每个匹配人员都有所有技能:

SELECT p.PersonName
FROM Person p
INNER JOIN PersonSkills ps ON p.PersonID = ps.PersonID
INNER JOIN Skills s ON ps.SkillID = s.SkillID
WHERE s.SkillName IN ('English', 'Math', 'Science')
GROUP BY p.PersonName
HAVING COUNT(DISTINCT s.SkillName) = 3;
cczfrluj

cczfrluj2#

你需要 having 条款。此外,建议始终为表指定别名,而不是在列之前使用整个表名。

select 
  p.PersonName, 
  s.SkillName
from Person p
left outer join PersonSkills ps
on p.PersonID = ps.PersonID 
left outer join Skills s
on ps.SkillID = s.SkillID
where s.SkillName in ('English','Math','Science')
group by
  p.PersonName, s.SkillName
having count(distinct s.SkillName) = 3

相关问题