计算每个人的技能

时间:2015-01-13 12:22:21

标签: mysql sql count

我正在尝试创建一个维恩图。我已经使用d3js的javascript。我现在需要的是以下内容。

有3个表

Person (id_person, name_person)
Skill (id_skill, name_skill)
Person_Skill(id_person, id_skill)

如何计算每个id_skill子集的人数( with sql )?

我已经编写了这个php脚本来创建id_skill的所有集合

 function powerSet($in, $minLength = 1) { 
   $count = count($in); 
   $members = pow(2,$count); 
   $return = array(); 
   for ($i = 0; $i < $members; $i++) { 
      $b = sprintf("%0".$count."b",$i); 
      //$out = array(); 
      $member = '';
      for ($j = 0; $j < $count; $j++) { 
         if ($b{$j} == '1') $member .= $in[$j]. ","; 
      } 
      if($member != '') $out = $member;
      if (count($out) >= $minLength) { 
         $return[] = $out; 
      } 
   } 
   return $return; 
} 

示例

Skill

id_skill       name_skill
1              PHP
2              SQL


Person

id_person         name_person
1                 'Name1'
2                 'Name2

Person_Skill

id_person              id_skill
1                      1
1                      2
2                      1

For the set of id_skill {1} => count = 1 (because only person 2 knows just this)
For the set of id_skill {2} => count = 0 (because person 1 also knows skill 1)
For the set of id_skill {1, 2} => count = 1 (person 1 knows both)

我想使用匹配所有ID的 IN CLAUSE 。数据库 MYSQL

1 个答案:

答案 0 :(得分:2)

您可以使用聚合字符串连接为每个人生成一组ID。然后你可以计算它们。

每个数据库都有不同的方法来进行聚合字符串连接。以下显示了MySQL的查询:

select skills, count(*) as cnt
from (select sk.id_person, group_concat(distinct sk.id_skill order by sk.id_skill) as skills
      from person_skill sk
      group by sk.id_person
     ) ps
group by skills;