需要查询MYSQL中的多对多关系

时间:2015-11-06 10:32:27

标签: mysql sql many-to-many

下面是表格结构:

我有三个表:员工,技能和employee_skills。

Employee: id, firstname, lastname, etc.....
Skill : id, title, description 
Emplyoee_skills : id, employee_id (FK of employee table), skill_id(FK of skill table)

现在,我想要以下输出:

Employee
Id    firstname    lastname
1     Rajnikant    Patel
2     Steve        Jobs
3     Sachin       Tendulkar
4     Ratan        Tata
Skill
Id    title        description
1     java         java
2     mongodb      mongodb
3     PHP          PHP
4     spring       Spring framework 
Employee_skills
Id    employee_id   skill_id
1     1             1
2     1             2
3     2             1
4     3             2

所以我想要一个可以返回具有传递技能的员工记录的查询:

让我们说,我传入where子句: s.title in(' mongodb',' java'),然后它应该返回记录:

Id   firstName        lastName
 1   Rajnikant        Patel

因为这名员工有这两种技能。

2 个答案:

答案 0 :(得分:1)

以下是如何操作:选择所有员工技能以获得所需技能,然后只保留员工的全部技能。

select *
from employee
where id in
(
  select employee_id 
  from employee_skills
  where skill_id in
  (
    select id 
    from skill
    where title in ('java', 'mongodb')
  )
  group by employee_id 
  having count(distinct skill_id) = 2
);

添加其他技能时,您必须检查3的数量,当然等等。

答案 1 :(得分:0)

以下查询将为您提供所需的结果。

SELECT e.id, e.firstname, e.lastname
FROM Employee e
JOIN Employee_skills es
ON es.employee_id = e.id
JOIN Skill s
ON es.skill_id = s.id
WHERE s.title IN ('mongodb', 'java')
GROUP BY e.id
HAVING count(s.id) = 2