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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程