MySQL: Select records where joined table matches ALL values

后端 未结 2 1126
青春惊慌失措
青春惊慌失措 2020-12-11 09:12

I\'m trying to find all employees with multiple skills. Here are the tables:

CREATE TABLE IF NOT EXISTS `Employee` (
  `ID` bigint(20) unsigned NOT NULL AUTO         


        
相关标签:
2条回答
  • 2020-12-11 09:51

    This will do it:

    SELECT EmpId, Name
    FROM
    (
       SELECT em.ID as EmpId, em.Name, es.ID as SkillID 
       FROM Employee em 
       INNER JOIN Emp_Skills es ON es.Emp_ID = em.ID
       WHERE es.Skill_ID IN ('1', '2')
     ) X
    GROUP BY EmpID, Name
    HAVING COUNT(DISTINCT SkillID) = 2;
    

    Fiddle here:

    The distinct is just in case the same employee has the skill listed twice.

    Thanks for the test data.

    0 讨论(0)
  • 2020-12-11 09:56

    You can do this with aggregation and a having clause:

    SELECT em.ID, em.Name 
    FROM Employee em INNER JOIN
         Emp_Skills es
         ON es.Emp_ID = em.ID
    GROUP BY em.id, em.name
    HAVING sum(es.Skill_id = '1') > 0 and
           sum(es.Skill_id = '2') > 0;
    

    Each condition in the having clause counts the number of rows for each employee that have a particular skill. The filter guarantees that both skills are present.

    0 讨论(0)
提交回复
热议问题