mySQL计数一对多链接的频率

时间:2011-02-23 23:09:46

标签: mysql

假设我有两个表:

people
=======
id
name

jobs
=====
id
jobname
person_id

人可能有很多工作。

我想计算人们有多少工作的频率。所以举个例子 10个人有0个工作, 15个人有1个工作, 3个人有2个工作, 2个人有3个工作

我可以按照以下方式计算每人的工作数量:

SELECT person.id, count(jobs.id) as jobcount
FROM jobs
WHERE person.id = jobs.person_id
GROUP BY person.id
ORDER BY trancount

personid   jobcount
 1          1
 2          1
 3          2
 ...

但是我总是在总结这些以获得频率。

1 个答案:

答案 0 :(得分:0)

您可以将它们分组到外部选择语句中吗?

SELECT jobcount, COUNT(peoplecount) FROM (
  SELECT person.id as peoplecount, count(jobs.id) as jobcount
  FROM jobs
  WHERE person.id = jobs.person_id
  GROUP BY person.id
) AS frequency GROUP BY jobcount