[英]I want to subtract 2 columns of two different tables
tbl_blood: tbl_血:
id|qty
1 14
2 15
3 16
tbl_blood_list: tbl_blood_list:
id|blood_quantity
1 1
2 1
3 1
My question is the tbl_blood table's column qty should subtract the blood_quantity column in tbl_blood_list's table.我的问题是 tbl_blood 表的列 qty 应该减去 tbl_blood_list 表中的 Blood_quantity 列。 I need codes that I can implement in my php mysqli.我需要可以在我的 php mysqli 中实现的代码。
I have tried this code but it really cannot work:我试过这段代码,但它真的无法工作:
$add_inv = "UPDATE tbl_blood
SET qty=(qty - '$blood_quantity')
WHERE id='$minus_blood_id' ";
There are more efficient ways to handle this kind of situation, you should consider a different structure for your program/tables, why having two separate tables when tbl_blood could be decremented directly.有更有效的方法来处理这种情况,您应该为您的程序/表考虑不同的结构,为什么在 tbl_blood 可以直接递减时有两个单独的表。
With your current structure, the code below works:使用您当前的结构,以下代码有效:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=blood', 'user', 'password');
/* Retrieve values to update */
$result = $pdo->query('
SELECT tb.id, (tb.qty - tbl.blood_quantity) n
FROM tbl_blood tb
LEFT JOIN tbl_blood_list tbl ON (tbl.id = tb.id)');
/* Update */
foreach ($result as $row)
$pdo->query('UPDATE tbl_blood SET qty = '.(int)$row['n'].' WHERE id = '.(int)$row['id'].' LIMIT 1');
?>
Result:结果:
tbl_blood
id|qty
1 13
2 14
3 15
Also:还:
If im not misjudging your question so you want to update join but in your table structure i can't find any common column if there is Any common column in both table so you can join and update your table in one statement i think id are common in both table if yes so try this如果我没有误判你的问题所以你想更新 join 但在你的表结构中我找不到任何公共列如果两个表中有任何公共列所以你可以在一个语句中加入和更新你的表我认为 id 很常见在两个表中,如果是,那么试试这个
$pdo->query("UPDATE tbl_blood AS tb JOIN tbl_blood_list AS tbl ON (tbl.id = tb.id) SET tb.qty = (tb.qty - tbl.blood_quantity)")
Please let me know if there is any problem or i misjudge your issue请让我知道是否有任何问题或我误判了您的问题
Hope it's help you.希望对你有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.