简体   繁体   English

如何通过累加最后一行值和插入值将值插入sql数据库

[英]how to insert a value to sql database by summing last row value and the inserting value

my table like this 我的桌子是这样的

id  debt   balance
1   1000   
2   500    
3   600   

i want table like this when i insert new debt value 当我插入新的债务值时,我想要这样的表

id  debt   balance
1   1000   1000
2   500    1500
3   600    2100

eg when i add debt value 1000 need to update balance as sum of the value 例如,当我添加债务值1000时需要更新余额作为值的总和

id  debt   balance
1   1000   1000
2   500    1500
3   600    2100
4   1000   3100
SELECT balance from table order by desc limit 1

after fetching last balance add it to the current dept value 提取上一个余额后,将其添加到当前的部门值中

$balance = $row['balance'];
$dept = $_POST['dept'];
$new_val = $dept+$balance;

add this new_val to the new balance field 将此new_val添加到新的余额字段中

INSERT INTO table (debt, balance) VALUES ('$dept', '$new_val');

You can try below 您可以在下面尝试

update tablename
set balance=debt+(select balance from tablename order by id desc limit 1)

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

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