PHP和MySQL字段的PHP总和回声

I have a database with the follow tables:

sales
expenses
taxes
earnings

When I sell some product it adds a item to sales, the same to expenses while I add expenses, taxes are added automaticly when selling and earnings too. They are on the same database but different tables.

I need to sum those fields together. I do it one by one without problems like this:

<?php
$query = mysqli_query($db, "SELECT SUM(total) AS `total` FROM `sales`");
while($result = mysqli_fetch_assoc($query)){
echo number_format($result['total'],0,',','.');} 
?>

and

<?php
$query2 = mysqli_query($db, "SELECT SUM(expense) AS `expense` FROM `expenses`");
while($result2 = mysqli_fetch_assoc($query2)){
echo number_format($result2['expense'],0,',','.');} 
?>

How do I sum those two and echo a result example:

sales - expense = value ?
<?php
    $query = mysqli_query($db, "SELECT SUM(total) AS `total` FROM `sales`");
    $query2 = mysqli_query($db, "SELECT SUM(expense) AS `expense` FROM `expenses`");
    $total_sales = 0;
    $total_expenses = 0;
    while($result = mysqli_fetch_assoc($query)){
        $total_sales = $total_sales + $result['total'];
        echo number_format($result['total'],0,',','.');
    }
    while($result2 = mysqli_fetch_assoc($query2)){
        $total_expenses = $total_expenses + $result['total'];
       echo number_format($result2['expense'],0,',','.');
   } 
?>

The sum would be $total_sales-$total_expenses.

Are you sure you will sum those two together?

There are at least good points you do those things separation. Firstly, the logic is very clearly. Secondly, if you have many data like those, when you sum them separately, those will not influence each other. Because when you select data and do some operation, if the data is not huge, it will be ok. But if it is huge data, both your database and your cpu and memory will have big pressure. Thirdly, when you select in database, it is not suggested doing operations such as sum, sub, division and multiplication, although database can do it. Because these operations are really wasting performance of database and computer.

Anyway, you still want to do that. Then you can try to left joint or right joint your table. You can use some foreign keys to connect these two tables and then you can do things which you wanna to do.