根据标准从另一个表中获取计数

时间:2015-01-06 14:48:15

标签: mysql sql

我有三张桌子,我想查询所有公司。但我想通过从people_history表中获取每个人的最后一条记录并将其与他们所工作的公司相匹配来了解活跃员工的数量。

Table: people

—————————————————————————————————————————————————
   id   |    name     |    ssn   |    phone     |
—————————————————————————————————————————————————
   1    |    John     |   9591   |   12341234   |
   2    |    Jane     |  1049    |   12340987   |
—————————————————————————————————————————————————

Table: people_history

—————————————————————————————————————————————————
id  |   person_id   |  company_id  |   time     |
—————————————————————————————————————————————————
1   |       1       |       5      |   stamp    |
2   |       1       |       7      |   stamp    |
3   |       2       |       2      |   stamp    |
4   |       1       |       2      |   stamp    |
—————————————————————————————————————————————————

Table: companies

————————————————
id  |   name   |
————————————————
1   |  Name 1  |
2   |  Name 2  |
…              |
————————————————

通过以下操作,我不会查找每个人的最后一条记录。

SELECT c.name AS company_name, COUNT(h.id) AS employees 
FROM companies c 
LEFT JOIN people_history h ON h.id = c.company_id 
GROUP BY c.id

有什么建议吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

未经测试但关闭工作:

SELECT c.name AS company_name, COUNT(h.id) AS employees 
FROM companies c 
LEFT JOIN (SELECT * 
           FROM people_history ph1 
           WHERE id = (SELECT MAX(id) 
                       FROM people_history ph2 
                       WHERE ph1.person_id = ph2.person_id)
           ) h ON h.id = c.company_id 
GROUP BY c.id

答案 1 :(得分:-1)

使用反连接很容易解决这个问题:

SELECT c.name AS company_name, COUNT(h1.id) AS employees 
FROM companies c 
LEFT JOIN people_history h1 ON h1.id = c.company_id
LEFT JOIN people_history h2 ON h2.id = c.company_id AND h2.person_id = h1.person_id AND h2.id > h1.id
WHERE h2.id IS NULL
GROUP BY c.id

这只计算person_history表中每个人的最后一条记录(最高id)。