简体   繁体   English

如何从两个表中减去

[英]How can i Subtract from two Tables

I want to subtract expenses total from income total tables, but I get a wrong figure whenever I run the query.我想从收入总额表中减去费用总额,但每次运行查询时都会得到一个错误的数字。

<?php
$query="SELECT income.Source
          ,SUM(income.Amount) as in_Amount
          ,SUM(expenses.Amount) as out_Amount
          ,SUM(income.Amount) - SUM(expenses.Amount) as total 
        FROM income as income
          , expenses";

$result=mysql_query($query);

while($row=mysql_fetch_array($result)){
    echo '<p class="stat"><span class="label label-danger">' . $row['total']. '</span> Naira Net Income</p>';
}
?>

The income table has a total of 40000 while the expenses table has a total of 5000, I get 30000 as a result of the query.收入表共有 40000,而费用表共有 5000,查询结果我得到 30000。

You are doing a join, you should do sub-queries.你正在做一个连接,你应该做子查询。 Try this:尝试这个:

SELECT Source, in_Amount, out_Amount, total_income - total_expenses FROM
(
  SELECT income.Source, SUM(income.Amount) as in_Amount,   SUM(expenses.Amount) as out_Amount,
  ( SELECT SUM(income.Amount) ) AS total_income,
  ( SELECT SUM(expenses.Amount) ) AS total_expenses
  FROM income as income, expenses
) t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM