减去两个子查询的结果

时间:2019-10-09 00:13:25

标签: mysql sql database

我的数据库中有3个表,分别是帐户,收入,支出。我希望有一个特定帐户的收入和支出的总和,然后得到这些总和的差额。这是表结构的摘要示例:

+--------------+
|   accounts   |
|--------------|
| id           |
| name         |
+--------------+

+--------------+
|   income     |
|--------------|
| id           |
| amount       |
| account_id   |
+--------------+

+--------------+
|   expense    |
|--------------|
| id           |
| amount       |
| account_id   |
+--------------+

这是我当前的查询:

select (t1.amount - t2.amount) as subtraction
from accounts a
inner join (
  select account_id, COALESCE(sum(amount), 0) as amount
  from income 
  where account_id = 4
) t1 on a.id = t1.account_id
inner join (
  select account_id, COALESCE(sum(amount), 0) as amount
  from expense 
  where account_id = 4
) t2 on a.id = t2.account_id

当我在两个表中都有记录时是否可以正常工作,所以我做错了吗?

0 个答案:

没有答案