首页 > 解决方案 > 知道每个表中的外键计数 - Postgres

问题描述

我希望你们都身体健康。我想显示外键出现在其子表中的次数。例如,我有一个带有主键“cin”的公司表,它链接到其他五个表,我想知道每个“cin”在其他表中出现了多少次。

我做了一个查询,它适用于少量数据,但是当我在 17GB 的数据库上运行它时,它需要永远(并且现在仍在运行),其中“ov”是数据库的名称,“opi” , 'zii', 'li', 'kvi' 和 'kra' 是 cin 作为外键链接的另外五个表。

Select c.cin, name, br_section, address_line,
(Select count(cin) from ov.opi
where cin = c.cin)  as opi_count,
(Select count(cin) from ov.zii
where cin = c.cin) as zii_count,
(Select count(cin) from li
where cin = c.cin) as li_count,
(Select count(cin) from ov.kvi
where cin = c.cin) as kvi_count,
(Select count(cin) from ov.krators
where cin = c.cin) as kra_count
from ov.company as c 
group by c.cin

如何优化它以获得快速结果?预期的输出有点像这样

cin   opi_count   zii_count   li_count   kvi_count   kri_count
1        56         NULL         2         NULL         9
2       NULL        140         NULL        10          23
3        2          90           10        NULL         2
4        34         NULL         89         3          NULL
5       NULL        34           2          9          NULL
.        .           .           .          .           .
.        .           .           .          .           .
.        .           .           .          .           .

谢谢你的tme,干杯!

标签: sqlpostgresqloptimization

解决方案


您的代码优化。唯一的改进是cin每个引用表中的索引。ov.opi(cin)所以一个关于,的索引ov.zii(cin),等等。


推荐阅读