我有一个足球幻想联盟剧本,每周我都会向用户添加一个积分,使用以下代码:
$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个用户之后,更新过程现在非常慢,有时会出现超时错误消息。
有没有办法重写此代码,以便更快地完成更新过程?
非常感谢,答案 0 :(得分: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.
理想情况下,您只需两次查询即可完成所有操作。