计算在同一 table 中引用主键的外键的出现次数

Count the occurrences of a foreign key that references a primary key in the same table

假设我有 table patients 看起来像这样:

+------------+------------+-----------+----------------+
| id_patient | first_name | last_name | recommended_by |
+------------+------------+-----------+----------------+
|          1 | Joe        | Bronson   |           NULL |
|          2 | Jack       | Jackson   |              1 |
|          3 | Jon        | Jonson    |              1 |
+------------+------------+-----------+----------------+

recommended_by 是表示患者 table 中另一行的外键。我想统计每位患者给出的建议数量。我使用了这个查询:

SELECT recommended_by, count(recommended_by)
FROM patients
GROUP BY recommended_by;

结果如下:

+----------------+-----------------------+
| recommended_by | count(recommended_by) |
+----------------+-----------------------+
|           NULL |                     0 |
|              1 |                     2 |
+----------------+-----------------------+

所以它 return 是 patient_id 和它的建议计数。但是,我想包括该患者的名字和姓氏。我如何创建查询以 return 列出所有提出建议的患者以及他们提出了多少?

例如,上面的结果会 return:

| id_patient | first_name | last_name | recommendations |
+------------+------------+-----------+-----------------+
|          1 | Joe        | Bronson   |               2 |

你开了个好头。如果我正在处理这个问题,我会首先编写一个子查询来获取每个 idrecommended_by 列中出现的次数。你做到了:

SELECT recommended_by, COUNT(*) AS numRecommendations
FROM patients
GROUP BY recommended_by;

然后您可以做的是在 id = recommended_by 的条件下将此子查询与您的原始查询连接起来。我建议 LEFT JOIN。如果患者从未推荐过某人,您将获得空值。使用 COALESCE 将其更改为 0:

SELECT p.*, COALESCE(t.numRecommendations, 0)
FROM patients p
LEFT JOIN(
   SELECT recommended_by, COUNT(*) AS numRecommendations
   FROM patients
   GROUP BY recommended_by) t ON t.recommended_by = p.id;

编辑

这是一个 SQL Fiddle 演示。