按匹配数量排序表

时间:2015-12-12 02:15:26

标签: sql sql-order-by

我有以下数据库架构:

申请人表:

applicant_id  | name 
--------------|----- 
      1       | Bill  
      2       | Tom  
      3       | Sam   
      4       | Alex  

技能表:

skill_id  | skill_name 
----------|-----------
    1     |    C++  
    2     |    java  
    3     |    html   
    4     |    PHP  

申请人技能(申请人和技能之间的多对多)

applicant_id  | skill_id 
--------------|-----------
      1       |     1  
      2       |     1  
      2       |     2   
      2       |     3  
      3       |     1  
      3       |     2  

我想选择所有申请人,但是根据特定技能列表的匹配数量来排序。

例如,如果我的技能列表是C ++,java和html,我希望它们像这样订购:

 name | matches
------|--------- 
 Tom  |    3   
 Sam  |    2 
 Bill |    1
 Alex |    0

任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:2)

  • Left Outer Join:要从applicants表中获取所有applicants,即使他没有skill Alex
  • Count AggregateCount每个applicants
  • 的技能
  • Order by:根据申请人拥有的技能数量订购结果

试试这个

SELECT          a.NAME , 
                Count(skill_id) AS matches 
FROM            applicants A 
LEFT OUTER JOIN 
                (SELECT     applicant_id, 
                            s.skill_id 
                 FROM       applicantskills 
                 INNER JOIN skills s 
                 ON         a.skill_id = s.skill_id 
                 WHERE      skill_name IN ('C++','java','html')) ask 
ON a.applicant_id= ask.applicant_id 
ORDER BY   matches DESC

答案 1 :(得分:0)

MM93 提出的解决方案几乎正确无误。内部查询中缺少GROUP BY子句,主查询中缺少IFNULL

如果有人感兴趣,这里是正确的解决方案:

SELECT a.applicant_name, IFNULL(sg.matches, 0)
FROM Applicants a
LEFT OUTER JOIN (
    SELECT a.applicant_id, count(s.skill_id) as matches
    FROM Applicants a
        JOIN ApplicantSkills aps ON aps.applicant_id = a.applicant_id
        JOIN Skills s ON aps.skill_id = s.skill_id
    WHERE s.skill_name IN ('C++','java','html')
        GROUP BY(a.applicant_id)
) sg ON a.applicant_id = sg.applicant_id
ORDER BY sg.matches DESC