1

我有一个足球幻想联盟脚本,每周我都会使用以下代码向用户添加一个积分:

$sql_user="select * from ".$prev."user ";

$re_user=mysql_query($sql_user);
while($d_user=mysql_fetch_array($re_user))
{
$userID=$d_user['id'];

$sql_addpointgroup="select * from ".$prev."addpoint group by weekno order by weekno";
$re_addpointgroup=mysql_query($sql_addpointgroup);
while($d_addpointgroup=mysql_fetch_array($re_addpointgroup))
{       
  $points=0;
  $sql_addpoint="select * from ".$prev."addpoint where weekno='".$d_addpointgroup['weekno']."'";
  $re_addpoint=mysql_query($sql_addpoint);
  while($d_addpoint=mysql_fetch_array($re_addpoint))
  {
    $points=$d_addpoint['points'];
    $sql_weekstatistic="select * from ".$prev."weekstatistic where weekno='".$d_addpointgroup['weekno']."' and userID='$userID' and playerID='".$d_addpoint['playerID']."'";
    $re_weekstatistic=mysql_query($sql_weekstatistic);
    if(mysql_num_rows($re_weekstatistic)>0)
    {
        $sql_update="update ".$prev."weekstatistic set points='$points' where weekno='".$d_addpointgroup['weekno']."' and userID='$userID' and playerID='".$d_addpoint['playerID']."'";

        mysql_query($sql_update);
    }
  }
}   
}

一开始这段代码运行良好,但注册用户数达到 500 个用户后,现在更新过程非常缓慢,并且有时会出现超时错误消息。

有没有办法重写这段代码,以便更快地完成更新过程?

提前谢谢了,

4

1 回答 1

0

嵌套循环意味着您可以轻松地运行数千个查询来获取您想要的数据。请尝试join

SELECT * FROM (SELECT * FROM addpoint GROUP BY weekno ORDER BY weekno) AS a JOIN addpoint USING weekno

使用该查询,您可以只循环一个结果数组。

至于更新,这是您可以使用的快捷方式。但是,只有weekno在表上定义为唯一索引时才能使用它。

INSERT INTO weekstatistic (weekno,points) VALUES {$vals} ON DUPLICATE KEY UPDATE points=VALUES(points)

{$vals}应该是以逗号分隔的 weekno/points 值列表:

$tmp = Array();
// build an array like so:
$tmp[] = "('".$weekno."','".$points."')";
// at the end of the loop:
$vals = implode(",",$tmp);
// now run the query.

理想情况下,您只需两个查询即可完成所有操作。

于 2012-10-01T20:22:24.347 回答