显示结果很慢

时间:2015-04-24 16:29:51

标签: php mysql wampserver

我有一个运行这个简单php代码的Wamp 2.4的Windows7系统

for ($year = 2004; $year <= 2015; $year++){
    for ($month = 1; $month <=12; $month++){
        mysql_connect("$host", "$username", "$password")or die("cannot connect");
        mysql_select_db("$db_name")or die("cannot select DB");
        $result = mysql_query("SELECT sum(Weight) FROM Lab WHERE YEAR(date)=$year  AND MONTH(date)= $month") or die(mysql_error());

        while ($rows = mysql_fetch_array($result)) {
            $weight = $rows['sum(Weight)'];
            ${'mes'.$month}=$weight;
            $weight3=$weight+$weight3;
            $weight=0;
        }
    }

    Echo $year, " Total - ", $weight3, "<br>";
    Echo $mes1, ", ", $mes2, ", ", $mes3, ", ", $mes4, ", ", $mes5, ", ", $mes6, ", ", $mes7, ", ", $mes8, ", ", $mes9, ", ", $mes10, ", ", $mes11, ", ", $mes12, "<br>";
    $weight3=0;
}

我的数据库大约有400000行,由于某种原因,显示任何结果大约需要40秒。如果我在mysql中执行相同的查询(逐年),则只需不到一秒钟。

我的代码有什么问题导致查询速度变慢吗?或者这是一个与Wamp相关的问题?

感谢您的帮助!

最终代码

mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$result = mysql_query("SELECT year(date), month(date), sum(Weight)
FROM Lab
WHERE date BETWEEN '2004-01-01' AND '2015-12-31'
GROUP BY year(date), month(date)");
   while ($rows = mysql_fetch_array($result)) {
       echo $rows ['year(date)']," ", $rows ['month(date)']," ",$rows['sum(Weight)'];
       Echo "<br>";
   } 

1 个答案:

答案 0 :(得分:6)

该代码非常低效。您连接到DB 11年* 12个月= 132次。循环也是必要的。为什么不在查询中全部完成呢?

SELECT year(datefield), month(datefield), sum(weight)
FROM youtable
WHERE datefield BETWEEN '2004-01-01' AND '2015-12-31'
GROUP BY year(datefield), month(datefield)