如何与表和减去与其他表的总和?

时间:2013-08-13 02:57:25

标签: mysql sql

我有两张桌子:

预算

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 我想要这个结果

抱歉,我是一个新手,我不能得到这个

1 个答案:

答案 0 :(得分: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;

如果您希望将其用于一个project_name,只需添加where子句:

where b.project_name = 'test'