在每个 table 与 Google Cloud SQL 中加入 3 table 与多个事件关联的相同唯一 ID
Joining 3 tables with multiples event associated to the same unique ID in each table with Google Cloud SQL
我在 Google Cloud SQL 中有三个 table :
事件table:
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
收入table:
id Income
A10117 1000
A10117 200
A10617 5000
A11017 3000
A11317 1500
A11317 560
A11417 2000
A12017 1500
费用table:
id Expenses
A10117 80
A10617 25
A10617 75
A11017 99
A11317 123
A11317 45
A11417 34
A11417 95
A12017 678
我希望输出是一个大的 table,其中每个事件只有一行,收入和支出正确相加。
例如在最终输出中我应该有一行 ID A10617 :
id Name Date Income Expenses
A10617 bar 2017-01-06 0:00:00 5000 100
etc...
我已经构建了一些查询,试图使用 WHERE
子句合并所有这些,但我的最终输出中有一些重复项。
所以我的问题是: 如何在一个查询中有效地合并这 3 个 table?我的理解是我需要先一个接一个地分别合并每个 table。我不知道该怎么做。
我理想的查询应该是这样的:
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
这假设所有事件 ID 都存在于收入和支出中。如果不是这种情况,请将 inner join 更改为 left join
编辑:
查询速度稍快:
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
我在 Google Cloud SQL 中有三个 table :
事件table:
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
收入table:
id Income
A10117 1000
A10117 200
A10617 5000
A11017 3000
A11317 1500
A11317 560
A11417 2000
A12017 1500
费用table:
id Expenses
A10117 80
A10617 25
A10617 75
A11017 99
A11317 123
A11317 45
A11417 34
A11417 95
A12017 678
我希望输出是一个大的 table,其中每个事件只有一行,收入和支出正确相加。
例如在最终输出中我应该有一行 ID A10617 :
id Name Date Income Expenses
A10617 bar 2017-01-06 0:00:00 5000 100
etc...
我已经构建了一些查询,试图使用 WHERE
子句合并所有这些,但我的最终输出中有一些重复项。
所以我的问题是: 如何在一个查询中有效地合并这 3 个 table?我的理解是我需要先一个接一个地分别合并每个 table。我不知道该怎么做。
我理想的查询应该是这样的:
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
这假设所有事件 ID 都存在于收入和支出中。如果不是这种情况,请将 inner join 更改为 left join
编辑: 查询速度稍快:
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