在两个不同的表中获得两列的差异?

时间:2013-11-14 10:31:55

标签: php mysql sql mysqli

我的sql代码执行但我不知道如何获得purchase_request total_qty和purchase_order数量的区别。

表Purchase_Order

counter | qty |      
---------------         
100001  | 10  |  
100001  | 10  |  
100001  | 10  |  
100004  | 30  |  

表Purchase_Request

counter | total_qty |
---------------------
100001  |     50    |  
100002  |     100   |  
100003  |     50    |  
100004  |     70    | 

我想像这样编码,但我不知道如何在我的代码中混合它。

a.total_qty-b.qty as balance 

这是我的代码

<?php
    $mysqli = new mysqli("localhost", "root", "", "test");

        $result = $mysqli->query("
        select a.counter,a.total_qty from purchase_request a inner join purchase_order b on a.counter= b.counter group by a.counter
        ");
        echo'<table id="tfhover" cellspacing="0" class="tablesorter" style="text-transform:uppercase;" border="1px">
            <thead>
            <tr>
            <th></th>
        <th>counter</th>
        <th>QTY</th>
        <th>balance</th>
            </tr>
            </thead>';
            echo'<tbody>';
        $i=1;   
    while($row = $result->fetch_assoc()){
        echo'<tr>
                <td>'.$i++.'</td>
                <td>'.$row['counter'].'</td>
                <td>'.$row['total_qty'].'</td>
                <td>'.$row['balance'].'</td>
            </tr>';
           }
        echo "</tbody></table>";

    ?>

2 个答案:

答案 0 :(得分:0)

你试过这个吗?

    select a.counter,
           a.total_qty,
           a.total_qty - b.qty balance 
      from (select counter,
                   sum(total_qty) total_qty
              form purchase_request
          group by counter) a 
inner join (select counter,
                   sum(qty) qty
              from purchase_order 
          group by counter) b 
        on a.counter= b.counter 
  group by a.counter

编辑:我知道了,你需要的是汇总你的数量,然后做数学

答案 1 :(得分:-1)

    select a.counter,
           a.total_qty,
           sum(a.total_qty) - sum(b.qty) as balance 
      from purchase_request a 
left inner join purchase_order b 
        on a.counter= b.counter 
  group by a.counter