首页 > 解决方案 > 连接和计算来自不同表的行

问题描述

因此,例如,我需要创建一个报告视图,将内容与一个人相关联。让我们说财产和狗。B和C之间没有联系

桌子person

桌子properties

桌子dogs

总结一下,我的报告如下所示:

select a.id, a.name, count(b.*), count(c.*) 
from person a 
  left join properties b on a.name = b.person 
  left join dogs c on a.name = c.person;

预期的结果是 A 人拥有 10 处房产和 20 条狗。

不知何故,这种连接完全增加了属性的数量并说出了正确的狗数量。如何修复连接?

标签: sqlpostgresql

解决方案


快速而肮脏的方法是使用count(distinct)

select a.id, a.name, count(distinct b.id), count(distinct c.id)
from table_a a left join
     table_b
     on a.name = b.person left join
     table_c c
     on a.name = c.person
group by a.id, a.name;

使用横向连接或子查询可能更快——特别是如果两个表中有很多行:

select a.id, a.name,
       (select count(*)
        from b
        where a.name = b.person
       ),
       (select count(*)
        from c
        where a.name = c.person
       ),
from table_a a ;

顺便说一句,如果 tablea有一个id,那应该用于链接到其他表而不是name.


推荐阅读