douji2520 2017-09-11 19:28
浏览 72
已采纳

更新mysql表中的列总和

I have a table named resources with the following columns:

ress1 
ress2 
prod1 
prod2 

I've tried the code indicated in the following links, but I'm still stuck...

How to find sum of multiple columns in a table in SQL Server 2005?

Auto update sum of rows & columns in a table

SQL How to Update SUM of column over group in same table

I want to run a script to UPDATE ress1 = ress1 + prod1 and the same with the ress2. So I want to update into a column the sum of the column itself and the corresponding column, doing that for every rows from the table.

Here is some code that seems easy for me, but not working...

$sql    = "SELECT * FROM ro_map";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result)){
$new_a = $row['a'] + $row['c'];
$new_b = $row['b'] + $row['d'];

"UPDATE ro_map SET a = '$new_a',b = '$new_b'";
} 

Ah...really sorry, guys :D I use mysql (with wampp server and HeidiSQL). And running this code don t give me any error ( if($conn->$sql == TRUE) will give me TRUE... SOLVED! Cool, thanks all, I've learned something :)

  • 写回答

1条回答 默认 最新

  • duan6832168 2017-09-11 19:35
    关注

    I think you're over-complicating it. If I understand you correctly, you can just do this in one transaction:

    Update    resources
    Set       ress1 = ress1 + prod1,
              ress2 = ress2 + prod2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?