左连接时计算不同的值

count distinct values while left joining

我有一个 table 看起来像这样:

people:
+-----+--------+-----+
|  id |   name | age |
+-----+--------+-----+
|  25 | Alpha |  30 |
| 113 |   Beta |  21 |
|  10 |   Test |  19 |
+-----+--------+-----+

还有一个像这样:

table2:
+-----+-----------+--------------+
|  id |   company | candidate_id | 
+-----+-----------+--------------+-
|   1 |  Google |           10 |    
|  36 | Microsoft |          113 |    
| 137 |  Google |           10 |    
|   2 | ITCompany |           10 |    
+-----+-----------+--------------+-------+

我想加入 table2 的人,这样我就可以找到与每个唯一个人 ID 对应的 DISTINCT 公司总数。我的最终结果应该是这样的:

+-----+--------+-----------+
|  id |   name | companies |
+-----+--------+-----------+
|  10 |   Test |         2 |
|  25 | Alpha |         0 |
| 113 |   Beta |         1 |
+-----+--------+-----------+

如何为公司做统计?

SELECT people.id, name, company
FROM people
    LEFT JOIN reports on people.id = table2.people_id

您可以按 people.id 分组并计算不同的公司:

SELECT p.id, p.name, 
       COUNT(DISTINCT r.company) companies 
FROM people p LEFT JOIN reports r
ON p.id = r.people_id
GROUP BY p.id;

我假设 id 是 table people 的主键。