Php 获取两个不同表中两列的差异?
我的sql代码执行,但我不知道如何获得采购请求总数量和采购订单数量的差异 表采购订单Php 获取两个不同表中两列的差异?,php,mysql,sql,mysqli,Php,Mysql,Sql,Mysqli,我的sql代码执行,但我不知道如何获得采购请求总数量和采购订单数量的差异 表采购订单 counter | qty | --------------- 100001 | 10 | 100001 | 10 | 100001 | 10 | 100004 | 30 | 表购买请求 counter | total_qty | --------------------- 100001 | 50 | 100002 |
counter | qty |
---------------
100001 | 10 |
100001 | 10 |
100001 | 10 |
100004 | 30 |
表购买请求
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>";
?>
你试过这个吗
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
编辑:我知道了,你需要的是把你的数量加起来,然后做数学运算它是有效的,但余额是40,我需要得到3 100001个数量计数器和减去总数量的总和。我应该得到20,因为余额情况越来越糟,$row['total\u qty']丢失了,100001的余额变成了120:/I得到了,我更改了,a.total\u qty,a.total\u qty-总和(b.qty)余额。只有一件事,为什么它在没有(as)的情况下工作?对不起,我是sqlI新手我再次更改了查询,我想这应该是您正在查找的致命错误:对非对象调用成员函数fetch_assoc()。计数器100001 balance=120是错误的,但计数器100004=40是正确的。为什么呢?但这是我的答案a.total_qty-总和(b.qty)作为余额,两个计数器=都是正确的。如果正确?当有多行具有相同计数器时,这将在采购订单和采购请求之间提供笛卡尔连接
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