0

我有 2 张桌子:

预算

id | project_name | total_budget
1  |    test      | 5000
2  |    try       | 200

费用

id|  project_name |paper|ballpen|total
1 | test          |100  |200    | 300
2 | test          |50   |50     |100
3 | try           |20   |0      |20

所以测试 project_name 的总数是 400

5000 - 400 = 4600 

试试 200 -20 = 180 我想要这个结果

对不起,我是新手,我买不到这个

4

1 回答 1

1

这是一个简单的聚合连接:

select b.project_name, b.total_budget, e.total as total_expense, b.total_budget - e.total as diff
from budget b left join
     (select project_name, sum(total) as total
      from expense e
      group by project_name
     ) e
     on b.project_name = e.project_name;

如果您想要一个项目名称,只需添加一个where子句:

where b.project_name = 'test'
于 2013-08-13T03:02:01.393 回答