sql - 知道每个表中的外键计数 - 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,干杯!
解决方案
您的代码已优化。唯一的改进是cin
每个引用表中的索引。ov.opi(cin)
所以一个关于,的索引ov.zii(cin)
,等等。
推荐阅读
- javascript - 双仪表板谷歌图表
- angular - 我有 npm 包的 repo 叉子。我应该如何使用它?
- authentication - 针对 Active Directory 的身份验证.. DirectorySearcher 的必要性
- c# - Filling a constructor with a loop
- python - 解决时scipy长时间停顿
- javascript - 在打字稿中解析 JSON 数组
- javascript - 错误:未捕获的异常:编译错误:
- php - 奏鸣曲 没有可用于当前请求的网站
- javascript - 如何在 JavaScript 中动态创建高阶函数?
- cpanel - PCI 扫描仪显示对端口 2078 和 2080 的 TLSv1 支持