sql - 连接和计算来自不同表的行
问题描述
因此,例如,我需要创建一个报告视图,将内容与一个人相关联。让我们说财产和狗。B和C之间没有联系
桌子person
- ID
- 姓名
桌子properties
- ID
- 人
- 姓名
桌子dogs
- ID
- 人
- 姓名
总结一下,我的报告如下所示:
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 条狗。
不知何故,这种连接完全增加了属性的数量并说出了正确的狗数量。如何修复连接?
解决方案
快速而肮脏的方法是使用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
.
推荐阅读
- javascript - javascript:单击数字框 - 增量不起作用
- reactjs - react js:安装下载的apk
- cassandra - 如何在数据中心另一台机器上的 cassandraDB 节点上读写?
- database - firebase 对多个 id 的分层查询是否比对单个 id 的简单查询更好?
- python - 如何管理 python pynput 模块中的键盘中断错误
- c# - svg 到 base64 没有第三方库 c#
- typescript - 将类型数组转换为打字稿中的函数参数类型
- spring - Spring Boot (v2.3.1): Spring Batch Partition w/JdbcPagingItemReader using SimplePartitioner Helper Class
- c - 为什么可以将未初始化的变量地址传递给函数的指针参数
- c# - 我正在尝试退出方法,但收到 CS0219 警告