我有三张桌子:
Project
PurchaseA
PurchaseB
项目示意图:
id | user_id | title | description | create_date
购买模式A:
id | project_id | amount | create_date
购买模式B:
id | project_id | amount | create_date
Project
有一堆独特的行,详细描述了不同的项目。这些项目中的每一个在PurchaseA
和中都有很多行PurchaseB
。我想要做的是从Project
字段id
和中选择所有行,以及title
中相关记录PurchaseA
总数和 中相关记录总数的总和PurchaseB
。
我可以让它彼此独立地工作,但是当我有两个连接时,数字最终会被大量夸大。
期望的结果
21732 Test Project A 84274.48
21747 Test Project B 18237.47
34714 Test Project C 183747.18
其中带有 FLOATS 的列是来自PurchaseA
和的相关行的总和PurchaseB
。
编辑
这是我当前的 SQL:
select
projects.id,
projects.title,
COALESCE(SUM(PurchaseA.amount), 0) as pledgetotal,
COALESCE(SUM(PurchaseB.amount), 0) as purchasetotal
from
projects
left join
PurchaseA ON (PurchaseA.project_id = projects.id)
left join
PurchaseB ON (PurchaseB.project_id = projects.id)
left join
WHERE
projects.title IS NOT NULL
projects.end_date < NOW()
group by projects.id
测试数据
Projects:
id title description create_date
623 Test Project A This is a test A 2013-01-01
624 Test Project B This is a test B 2013-01-02
PurchaseA
id project_id amount create_date
1 623 100 2013-01-02
2 623 125 2013-01-02
3 624 200 2013-01-03
4 623 150 2013-01-03
5 624 50 2013-01-04
PurchaseB
id project_id amount create_date
1 623 110 2013-01-02
2 624 105 2013-01-02
3 623 215 2013-01-03
4 623 100 2013-01-03
5 624 150 2013-01-04
如您所见,每个项目在每个相关表中都有多行。我想从每个表中获取总和,然后将它们加在一起。