显示结果很慢

very slow to show result

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

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>";
   } 

该代码效率极低。您连接到数据库 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)