0

我建立了一个每天收集信息的数据库。就像日历一样,数据库存储会员的每日金额。如果月份不匹配任何现有月份(MY),数据库将创建一个新的 html 月份表。我已经解决了这个问题,如下:

mysql_query("something goes here");
while(condition)
{
    mysql_query("something goes here")
    while(condition)
    {
        mysql_query("something goes here");
        while()
        {
            ....................
        }
        ........................
    }
}

当我发现这个算法时,它运行良好。但是,几天后,它给我的服务器带来了沉重的负担。然后我在 PHP 中尝试了相同的算法(但我不能这样做)。我怎样才能让它运行得更快?代码如下:

        $q2=mysql_query("SELECT  a.member_id,a.dates,MONTH(dates) AS months,
                        YEAR(dates)AS years,sum(amount) as sums
                        FROM account AS a
                        left join member as m
                        on(a.member_id=m.member_id)
                        GROUP BY (SELECT EXTRACT(YEAR_MONTH FROM dates))
                        ORDER by dates DESC
        ");
        $k=0;
        while($data2=mysql_fetch_assoc($q2))
        {
            $months=$data2['months'];
            $years=$data2['years'];
            $daten = new DateTime($data2['dates']);

            print "<tr><th align='left'><b>".$daten->format('F-Y')."</b></th>";

            $q3=mysql_query("select * from member");

            while($data3=mysql_fetch_assoc($q3))
            {
                $id3=$data3['member_id'];
                $q4=mysql_query("
                                SELECT SUM(amount) AS total FROM account
                                WHERE member_id=$id3
                                AND month(dates)=$months
                                AND year(dates)=$years                              
                            ");
                while($data4=mysql_fetch_assoc($q4))
                {
                    $total=$data4['total'];

                    print "<td class='total'>".number_format($total)."</td>";
                }
            }
            print "<td class='total'><b>".$data2['sums']."</b></td></tr>";
            $k=$k+$data2['sums'];
        }
4

2 回答 2

2

除其他事项外:

  • 您正在SELECT * FROM member为第一个查询中的每一行运行查询。这个查询是独立于循环的,所以每次都重新运行是很浪费的。

  • 对于SELECT * FROM member查询的每个结果,您都在运行另一个查询 ( SELECT SUM(amount) AS total FROM account ...)。这个查询有几个问题:

    • 首先,可以使用 a 将此查询组合到上一个查询中GROUP BY,以避免必须为每个成员运行一个查询。就像是:

      SELECT member_id, SUM(amount) AS total FROM account WHERE ... GROUP BY member_id

    • 其次,您正在使用MONTH(dates) = $months AND YEAR(dates) = $years. 这是低效的,因为它强制服务器检查每一行;如果 . 上有适当的索引,则将其转换为dates(例如dates BETWEEN '$year-$months-01' AND '$year-$months-31')上的范围会加快速度dates

一般来说:避免循环查询。生成页面所涉及的查询数量应尽可能地始终是一个很小的、几乎恒定的数字。它不应该随着您的数据而增长。

于 2013-01-14T19:19:21.710 回答
0

您是否在 MySQL 数据库中设置了适当的索引?这可能会导致巨大的性能差异。http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

于 2013-01-14T19:07:24.720 回答