dqpu4988 2015-07-08 05:25
浏览 36

在循环关联数组时优化SQL更新

I'm iterating over an associative array with key value pairs. Inside the loop there's an SQL Update, SQL Select and another Update. Is it possible to combine two or all of those statements in one to reduce execution time? In short: the foreach is looping through given points to a player. It should add those points to the points table. It then should take the players total current points and add the new points (value of the foreach) to that total. Then, it should update the players total score.

This code does work and give correct results, but just takes to long to run when having lots of players. It gives me a total execution time of 12 seconds to run this script with only 800 players so far.

foreach($arrPoints as $key => $value)
{
    $sqlUpdatePoints = "UPDATE tblPoints SET Points = '$value' WHERE Game='FPS' AND PlayerId ='$key' AND Gamenumber = 2";

    $PointsBefore=0;$PointsAfter=0;
    $sqlReadPoints = "SELECT TotalPointsBefore, TotalPointsAfter FROM tblplayer WHERE Id=$key";
    $parameters=array('');
    $resultReadPoints = dataQuery($sqlReadPoints,$parameters);
    foreach($resultReadPoints AS $rowRP)
    {
        $PointsBefore= $rowRP['TotalPointsBefore'];
        $PointsAfter= $rowRP['TotalPointsAfter'];
    }
    $NewTotalBefore= $PointsBefore + $value;
    $NewTotalAfter= $PointsAfter+ $value;
    $sqlUpdateNewPoints = "UPDATE tblplayer SET TotalPointsBefore='$NewTotalBefore', TotalPointsAfter='$NewTotalAfter' WHERE Id=$key";
}
  • 写回答

1条回答 默认 最新

  • dongshen6060 2015-07-08 06:26
    关注

    I solved the issue. I could eliminate the foreach by incrementing the value inside the update statement itself. This reduces execution time a lot because no lookup needs to happen. Final execution not included in below sample, should be done using PDO as statet by @ArtisticPhoenix

    foreach($arrPoints as $key => $value)
    {
        $sqlUpdatePoints = "UPDATE tblPoints SET Points = '$value' WHERE Game='FPS' AND PlayerId ='$key' AND Gamenumber = 2";
        $sqlUpdateNewPoints = "UPDATE tblplayer SET TotalPointsBefore=TotalPointsBefore+$value, TotalPointsAfter=TotalPointsAfter+$value WHERE Id=$key";
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP