在while循环中加速mysql查询

时间:2013-10-28 15:44:57

标签: php mysql sql performance optimization

我有以下查询:

while ($start_date <= $end_date) {

            $date_array[] = date('d/m/Y H:i:s', strtotime($start_date));

            $start_date_interval = date('Y-m-d H:i:s', strtotime($start_date) + $interval);
            echo date('d/m/Y H:i:s', strtotime($start_date)) . ' ------> ';


            $query = "SELECT COUNT(id) AS call_count FROM callsepaug "
                    . "WHERE (i_billable = 1 AND ((start_time >= '$start_date' AND start_time < '$start_date_interval') "
                    . "OR (start_time > '$start_date_past' AND start_time < '$start_date_interval' "
                    . "AND end_time >= '$start_date')));";


            $result = mysqli_query($connection, $query);

            $row = mysqli_fetch_array($result, MYSQLI_ASSOC);

            $data[] = $row['call_count'];
            echo $row["call_count"] . ' active calls.<br>';

            $start_date = date('Y-m-d H:i:s', strtotime($start_date) + $interval);
            // echo $start_date . '<br>';
        }

但是这个查询太慢了。该数据库包含大量数据。检查开始和结束给定时间的15分钟间隔的查询大约需要45秒。如何大大提高速度?

1 个答案:

答案 0 :(得分:2)

最好在循环外编写所有查询,因为它会为每次迭代执行查询 获取开始日期和结束日期之间的所有记录,并在循环中处理它们