mysql - 使用 Google Cloud SQL 连接 3 个表,其中多个事件关联到每个表中的相同唯一 ID
问题描述
我在 Google Cloud SQL 中有三个表:
事件表:
id Name Date
A10117 foo 2017-01-01 0:00:00
A10617 bar 2017-01-06 0:00:00
A11017 barfoo 2017-01-10 0:00:00
A11317 foofoo 2017-01-13 0:00:00
A11417 barbar 2017-01-14 0:00:00
A12017 foobar 2017-01-20 0:00:00
收入表:
id Income
A10117 1000
A10117 200
A10617 5000
A11017 3000
A11317 1500
A11317 560
A11417 2000
A12017 1500
费用表:
id Expenses
A10117 80
A10617 25
A10617 75
A11017 99
A11317 123
A11317 45
A11417 34
A11417 95
A12017 678
我希望输出是一张大表,其中每个事件只有一行,收入和费用总和正确。
例如,在最终输出中,我应该有一行 ID A10617 :
id Name Date Income Expenses
A10617 bar 2017-01-06 0:00:00 5000 100
etc...
我已经构建了一些查询来尝试整合所有这些 usingWHERE
子句,但我的最终输出中有一些重复项。
所以我的问题是:如何在一个查询中有效地合并这 3 个表?我的理解是我需要一个接一个地分别合并每个表。我不知道该怎么做。
我理想的查询是这样的:
SELECT id,Name,Date,sum(Income),sum(Expenses)
FROM Event e, Income i, Expenses ee
WHERE e.id = i.id = ee.id
GROUP BY id,Name,Date
解决方案
select e.id, (select sum(Income) from income where id=e.id) as income, sum(ex.Income) as expenses from event as e inner join expenses as ex on e.id=ex.id group by e.id
This assumes all event ids are there in both income and expenses. If it is not the case change inner join to left join
Edit: Little faster query:
select e.id, (select sum(Income) from income where id=e.id) as income, (select sum(Income) from expenses where id=e.id) as expenses from event as e
推荐阅读
- macos - 在两台 Mac 上设置密钥后,Mac 使用 SSH 询问密码
- r - 按其值转换表中的列
- sql - Oracle SQL:如何使用“IN 或 NOT IN 或其他”关键字检查给定的员工 ID 列表中不存在哪些记录?
- javascript - 应用程序中的计数器未按预期运行
- javascript - VUEX Getter = 数组内的过滤器数组
- laravel - 如何在 laravel 项目中同时使用 web 的守卫和 api 的守卫?
- java - 最小的java文件
- python - 查找索引numpy python
- python - 用python点击iframe中的按钮
- azure-devops - 如何添加 DevOps 权限