我有一个足球幻想联赛的php脚本,有20支球队和400多名球员被分配到这些球队,我有500个用户。
每周都应该为每个球员分配一个积分,这样最终每个用户都会从他的队形中获得一个总积分,这将产生本赛季的排名。
第一周的积分是正常添加的,但对于第二周的积分,addpont部分变得非常慢,对于第三周的积分会出现套接字超时错误。
这是我在为用户添加点数时使用的代码:
// Adding Point To the user player list
$sql_user="select * from ".$prev."user LIMIT 0, 100 ";
$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);
}
}
}
}
我已经将每次提交的用户数量限制为100个,即使如此,代码仍然很慢。
速度缓慢的原因是只有使用此代码,其他网站部分才能正常工作。
有没有其他更快的方法来编写代码,或者如果还有其他事情我可以做?
非常感谢,
select * from
我希望您知道SELECT
查询中*
的含义。意思是ALL COLUMNS
。您不需要每行中所有列的值。在查询中要具体,只选择需要的列。
例如,这个查询:
$sql_weekstatistic="select * from ".$prev."weekstatistic where weekno='".$d_addpointgroup['weekno']."' and userID='$userID' and playerID='".$d_addpoint['playerID']."'";
你已经有了的价值
weekno @ $d_addpointgroup['weekno']
userID @$userID
playerID @$d_addpoint['playerID']
基于其他查询。
但是,您仍然使用SELECT * FROM
。
这是我关于性能和SQL的小提示。
BTW,使用mysql_real_escape_tring()
保护您的查询,或者,甚至更好的是,按照@lshikawa的建议,移动到mysqli
或PDO
。
我不打算提及SQL注入的问题,只是建议您遵循本线程中其他人的建议。说真的,如果你要求人们提交个人数据存储在你的数据库中,你应该保护他们免受数据被盗的影响。
你的过程缓慢的原因可能有两个。
首先,当只需要一个查询时,您将使用5个查询。你向数据库询问了大量的数据,你用这些数据来问它更多的问题——在不知道你的模式的情况下,很难给你一个有效的替代品,但类似于:
update ".$prev."weekstatistic
set points = ap.points
from weekstatistic ws,
addpoint ap,
user u
where weekno = //work out the current weeknumber
and userID = u.userID
and playerID = ap.playerID'
这应该实现相同的功能,但只需要一个查询;那应该快得多。
其次,您的表上可能没有正确的索引——这是"随着表中数据的增加,查询速度变慢"的典型原因。阅读EXPLAIN,并添加一些索引。