抓取特定列中具有最高值的行

时间:2011-12-01 18:38:13

标签: php mysql

我有一个简单的表,存储与下载绑定的唯一ID。我要做的是生成创建的最新ID的CSV。每次生成密钥时(一次只能有1到100个密钥),UNIX时间戳将与这些密钥一起存储。

我生成的CSV文件很好,但我无法使MAX功能正常工作。我的报告生成器如下:

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=codes.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Unique Codes'));

// fetch the data
/** database username and pass removed **/
$rows = mysql_query('SELECT uniqueid FROM downloadkeys');

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

4 个答案:

答案 0 :(得分:2)

这样的事情应该有效。我正在对列名做出假设,因此您需要更改代码以匹配您的架构。

// fetch the data
/** database username and pass removed **/
$rows = mysql_query('SELECT uniqueid FROM downloadkeys ORDER BY timestamp DESC LIMIT 10');


编辑(未经测试):

// fetch the data
/** database username and pass removed **/
$rows = mysql_query('SELECT uniqueid, timestamp FROM downloadkeys ORDER BY timestamp DESC LIMIT 100');

$prev_timestamp = NULL;
$uniqueids = array();

while ($row = mysql_fetch_assoc($rows)) {
    if ($prev_timestamp !== NULL && $row['timestamp'] != $prev_timestamp)
        break;

    $uniqueids[] = array('uniqueid' => $row['uniqueid']);
    $prev_timestamp = $row['timestamp'];
}

foreach ($uniqueids AS $row)
    fputcsv($output, $row);

答案 1 :(得分:1)

SELECT id FROM table ORDER BY timestamp DESC LIMIT 5

您需要ORDER BY时间戳降序才能获得最新信息。 LIMIT X只返回X个记录。

答案 2 :(得分:1)

......或者,可能:

SELECT uniqueid FROM downloadkeys WHERE timestamp=MAX(timestamp)

答案 3 :(得分:1)

select uniqueid 
  from downloadkeys
 where creationTime = ( select max(creationTime) 
                          from downloadkeys )

或者如果您更喜欢加入

select uniqueid 
  from downloadkeys
 inner
  join ( select max(creationTime) maxCreationTime
           from downloadkeys ) dk
    on creationTime = dk.maxCreationTime