以下是我的数据库相关部分的简化版本:
Person:
id
PersonSkills:
person_id
skillname
ability
Position:
id
PositionSkills:
position_id
skillname
ability
一个人可以拥有任意数量的个人技能,比如在这个例子中,我们的用户有6个。
一个职位可能需要很多职位技能,比如说在这个例子中,这个职位需要3个。
我需要一个查询,它将确定与此职位相关的所有职位技能是否都存在于与此人相关的人员技能中。(我还需要确保杀人犯的能力大于职位技能的能力,但我认为一旦我找到了给我带来麻烦的部分,这将很简单。)
提前谢谢你,
杰森
编辑
下面是我要找的更多细节:
PersonSkills
+-------------+---------+---------+
| person_id | skill | ability |
+-------------+---------+---------+
| 1 | A | 5 |
| 1 | B | 4 |
| 1 | C | 5 |
| 1 | D | 4 |
| 1 | E | 5 |
+-------------+---------+---------+
PositionSkills
+-------------+---------+---------+
| position_id | skill | ability |
+-------------+---------+---------+
| 5 | A | 3 |
| 5 | B | 3 |
| 5 | C | 3 |
| 6 | A | 3 |
| 6 | B | 3 |
| 6 | Z | 3 |
+-------------+---------+---------+
从我是用户1的事实出发,我想要一个查询告诉我,我有资格胜任职位5,因为我有它所要求的技能a、B和C,但是我没有资格胜任职位6,因为我缺乏技能Z
再次感谢,
杰森
最佳答案
尝试此解决方案:
SELECT
a.id,
(COUNT(c.position_id) = (SELECT COUNT(*) FROM positionskills WHERE position_id = <position_id here>)) AS isQualified
FROM
person a
LEFT JOIN
personskills b ON a.id = b.person_id
LEFT JOIN
positionskills c ON
b.skillname = c.skillname AND
b.ability >= c.ability AND
c.position_id = <position_id here>
GROUP BY
a.id
WHERE
a.id = <person_id here>
如果此人符合条件,
isQualified
将1
否则将0
编辑:根据问题的澄清,要获得该人员符合条件的所有职位,请使用以下解决方案:
SELECT
a.position_id
FROM
(
SELECT bb.position_id, COUNT(*) AS skillshave
FROM personskills aa
INNER JOIN positionskills bb ON aa.skillname = bb.skillname AND aa.ability >= bb.ability
WHERE aa.person_id = <person_id here>
GROUP BY bb.position_id
) a
INNER JOIN
(
SELECT position_id, COUNT(*) AS skillsrequired
FROM positionskills
GROUP BY position_id
) b ON a.position_id = b.position_id AND a.skillshave = b.skillsrequired