保存MySQL查询的每个第N条记录,同时保持下降限制

时间:2015-03-25 16:50:50

标签: php mysql

有没有办法在保持下降限制的同时返回MySQL请求的每个第N条记录?否则,是否可以只将每个Nth请求保存到我的PHP数组中?数据最终回显到javascript以向Google Chart提供数据,显然10080条记录无法创建平滑的图形。

$myquery = "SELECT * 
FROM ( 
    SELECT 
        @row := @row +1 AS rownum, dateTime, outTemp, dewpoint
    FROM ( 
        SELECT @row :=0) r, archive 
    ) ranked 
    WHERE rownum % 5 = 1";

$query = mysql_query($myquery);

 if ( ! $query ) 
 {
        echo mysql_error();
        die;
}

$table=array();
$table['cols'] = array(
    // Chart Labels (i.e. column headers)
    array('label' => 'dateTime', 'type' => 'number'),
    array('label' => 'Temp', 'type' => 'number'),
    array('label' => 'Dew', 'type' => 'number')
);

$rows = array();

while($r = mysql_fetch_assoc($query))
{
    $temp = array();
    $temp[] = array('v' => (int) $r['dateTime']); 
    $temp[] = array('v' => (int) $r['outTemp']);
    $temp[] = array('v' => (int) $r['dewpoint']);
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);

更新:

我可以使用How do you select every n-th row from mysql中的说明选择每个第N行,但它不能解决如何保留我的降序滤波器。我试图以类似于使用DESC LIMIT 10

的方式选择数据集的最后x行

2 个答案:

答案 0 :(得分:0)

SELECT @row_number := NULL;
SELECT
    @row_number := IFNULL(@row_number, 0) + 1 AS row_number,
    Column1,
    Column2,
    ColumnN
FROM the_table
WHERE @row_number % 2 = 0
ORDER BY Column1

答案 1 :(得分:0)

我通过获取行计数并根据行数N(本例中为$ interval)和所需数据范围设置限制来解决问题。此解决方案将数据按降序排列在限制范围内,同时使数据本身保持在Google Charts图表的正确顺序中。

// Get a row count ... ... ...
$count = mysql_query("select count(1) FROM archive");
$grabCount = mysql_fetch_array($count);

 if ( ! $count ) 
 {
        echo mysql_error();
        die;
}




// ROW BOUNDARIES  ... ... ...
$hour = 60;
$day = 1440;
$week = 10080;
$month = 43200;
$year = 525600;

$timeSpan = $day;
$interval = 30;

$filter = $timeSpan / $interval;
$rows = (int) ($grabCount[0] / $interval);

$rowStart = ($rows - $filter);
$rowEnd = $rows;


// Query the Database for what you want
$myquery = "SELECT * 
FROM ( 
    SELECT 
        @row := @row +1 AS rownum, dateTime, outTemp, dewpoint
    FROM ( 
        SELECT @row :=0) r, archive 
    ) ranked 
WHERE rownum % $interval = 1 LIMIT $rowStart,$rowEnd";