简体   繁体   English

从一个表中添加多个字段的值,并将其减去到另一个表中的字段中的PHP

[英]Add values of multiple fields from one table and subtract it to a field from another table in php

I have two tables : contract bill . 我有两张桌子: contract bill
contract table contains following fields(contId (PK), contractNumber, quantity, etc..). contract表包含以下字段(contId(PK),contractNumber,数量等。)。
bill contains following fields(billId (PK), billNo, contId, checkMtr, etc...). bill包含以下字段(billId(PK),billNo,contId,checkMtr等)。

Here every contract can have multiple bills. 在这里,每个合同可以有多个账单。 What I am trying to do is add all the inwMtr of a contract and deduct that from the quantity and display the final mtrs as Pending Mtr. 我想做的是add合同的所有inwMtr并从quantity扣除,然后将最终的inwMtr显示为Pending Mtr。

Here is what I have tried: 这是我尝试过的:

<?php

include("dbconnection.php");

$sql1 = mysql_query("SELECT quantity FROM contract WHERE contId = '25'");
while($result1  = mysql_fetch_array($sql1))
{
//echo "$result1[quantity]";
//echo "<br/>";


//echo "<br/>";

$sql2 = mysql_query("SELECT checkMtr FROM bill WHERE contId = '25'");
while($result2  = mysql_fetch_array($sql2))
{
//echo "$result2[checkMtr]";
//echo "<br/>";

$a = $result1['quantity'] - $result2['checkMtr'];
echo "$a";
echo "<br/>";

}
echo "<br/>";

}
echo "<br/>";
?>

Here it does subtract checkMtr from quantity but it does it for every bill. 在这里,它的确从数量中减去了checkMtr,但它对每张账单都这样做。 It doesn't add checkmtrs of all the bills and then subtract. 它不会添加所有账单的checkmtrs,然后减去。

Any suggestions? 有什么建议么?

$sql2 = mysql_query("SELECT sum(checkMtr) checkMtr FROM bill WHERE contId = '25'");
if (mysql_num_rows($sql2) == 1) {
  $result2  = mysql_fetch_array($sql2);
  $a = $result1['quantity'] - $result2['checkMtr'];
} else {
  $a = $result1['quantity'];
}
echo $a;

There's also no need for the while loop after the first query. 在第一个查询之后也不需要while循环。 It can never return more than one row, since you're selecting the row by primary key. 由于您要通过主键选择该行,因此它永远不能返回多于一行。

You can also combine this into one query: 您还可以将其合并为一个查询:

SELECT quantity - ifnull(sum(checkMtr), 0) result
FROM contract c
LEFT JOIN bill USING (contId)
WHERE c.contId = '25'

To do this for all contracts, use GROUP BY : 为此,请使用GROUP BY

SELECT c.contId, quantity - ifnull(sum(checkMtr), 0) result
FROM contract c
LEFT JOIN bill USING (contId)
GROUP BY c.contId

SQLFIDDLE SQLFIDDLE

Replace checkMtr both in the SQL statement and in your subtraction line with 将SQL语句和减法行中的checkMtr替换为

SUM(checkMtr)

and it will work. 它会工作。

If I understand you correctly you want checkMtr to be a single number that is subtracted? 如果我理解正确,那么您希望checkMtr是一个被减去的数字吗?

This will add all of the checkMtr results and will output that sum. 这将添加所有checkMtr结果并输出该总和。

SELECT sum(checkMtr) FROM bill WHERE contId = '25'

Also if contId is being submitted from the user I hope you are validating the data 另外,如果要从用户提交contId,我希望您正在验证数据

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

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