繁体   English   中英

MYSQL:根据另外两个表的连接计算一个表中的行数

[英]MYSQL: Count the number of row in one table based on the join of two other tables

我有三个表,条目、机构和医生。 这是表数据的最小示例:

参赛作品

| keyid  | doctorid | 
---------------------
|  1     |    23    |
|  2     |    13    | 
|  3     |    23    | 
|  4     |    13    | 
|  5     |    23    |
|  6     |    42    | 
|  7     |    5     | 

机构

| name   |
----------
|  One   |
|  Two   |
|  Three |
|  Four  |
|  Five  |
|  Six   |

医生

| uid      |   inst   | 
-----------------------
|  23      |    Three |
|  13      |    Six   | 
|  3       |    Four  | 
|  42      |    Six   | 
|  5       |    One   |

我需要知道的是每个机构的条目数量。 但是,机构通过 DOCTORS 表链接到条目。 所以在这种情况下的结果应该给我这个:

结果

| name     | count |
--------------------
| One      |  1    |
| Two      |  0    |
| Three    |  3    |
| Four     |  0    |
| Five     |  0    |
| Six      |  3    |

我什至不知道如何开始编写这个查询。 任何帮助将不胜感激。

这可以通过连接所有三个表的聚合查询来解决,例如:

SELECT
    i.name,
    COALESCE(COUNT(e.keyid), 0) cnt
FROM
    institution i
    LEFT JOIN doctors d ON d.inst = i.name
    LEFT JOIN entries e ON e.doctorid = d.uid
GROUP BY i.name

使用您的示例数据, DB Fiddle 上的这个演示返回:

| name  | cnt |
| ----- | --- |
| One   | 1   |
| Two   | 0   |
| Three | 3   |
| Four  | 0   |
| Five  | 0   |
| Six   | 3   |

PS:根据您的数据,您可能想要使用COUNT(DISTINCT e.keyid)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM