【发布时间】:2012-07-23 13:52:01
【问题描述】:
此脚本使用 php 和 mysql 计算一分钟滚动平均值,以减少异常值对我的数据的影响(一分钟 = 6 10 秒行)。它可以正确计算所有内容,但效率不足以一次处理超过 150 行。我想一次做尽可能多的行,可能在 5-10,000 之间,因为我的表超过 150,000,我每天输入大约 8,000 行。
关于如何使这个脚本更有效地运行,有人有什么建议吗?
谢谢!
<?php
//connect to database
mysql_connect("localhost","user","password");//database connection
mysql_select_db("database");
$result = mysql_query("SELECT Timestamp FROM table");
if (!$result) {
die('Could not query:' . mysql_error());
}
//get number of rows in table
$resultA = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($result);
echo "There are $num_rows rows.</br>";
//select column to be averaged
$resultB = mysql_query("SELECT PortRPMSignal FROM table");
if (!$resultB) {
die('Could not query:' . mysql_error());
}
//set start equal to the first row you want to calculate the averages from, likely the first null row
$start = 5;
//calculate 1 minute average, the average is correct
for($i = $start; $i<$num_rows; $i++){
$output = mysql_result($result,$i);
$test = mysql_result($resultB,$i)+mysql_result($resultB,$i-1)+mysql_result($resultB,$i-2)+mysql_result($resultB,$i-3)+mysql_result($resultB,$i-4)+mysql_result($resultB,$i-5);
$test2 = $test/6;
$round = round($test2,4);
$temp = mysql_query("SELECT Timestamp FROM table");
if(!$temp){
die('Could not query:' . mysql_error());
}
//gets timestamp at row $i, and inserts new average value into that row in RPMAve column
$time = mysql_result($result,$i);
mysql_query("UPDATE table SET PortMinuteAveRPM = $round WHERE Timestamp = '$time'");
}
【问题讨论】:
-
你必须使用 MySQL 吗?看起来你不需要它。
-
如
mysql_query()函数的 PHP 手册中所述:不鼓励使用此扩展。相反,应该使用MySQLi 或PDO_MySQL 扩展名。另请参阅MySQL: choosing an API 指南和related FAQ 了解更多信息。 -
我开始使用 MySQL 来自动执行我所做的分析,而不是使用 Excel,您还有其他建议吗?
标签: php mysql performance average