【问题标题】:Grab row(s) with highest value in specific colum抓取行)在特定列中具有最高值
【发布时间】:2011-12-01 18:38:13
【问题描述】:

我有一个简单的表,用于存储与下载相关的唯一 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);

【问题讨论】:

    标签: php mysql


    【解决方案1】:

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

    // 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);
    

    【讨论】:

    • 我不能使用 LIMIT,因为最近的时间戳可能有 1 行或 100 行。
    • 哦。那会更难。有关基于 SQL 的示例,请参阅 stackoverflow.com/questions/2643314/mysql-group-by-limit。或者,如果 100 是最多生成的,您可以LIMIT BY 100 并使用 PHP 过滤掉不属于的时间戳。
    • 用一个使用 PHP 的示例(未经测试)更新了我的答案。
    【解决方案2】:
    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
    

    【讨论】:

      【解决方案3】:

      SELECT id FROM table ORDER BY timestamp DESC LIMIT 5

      您需要ORDER BY 时间戳降序获取最新信息。 LIMIT X 将只返回 X 条记录。

      【讨论】:

        【解决方案4】:

        ……或者,可能:

        SELECT uniqueid FROM downloadkeys WHERE timestamp=MAX(timestamp)

        【讨论】:

        • WHERE timestamp=(SELECT MAX(timestamp) FROM downloadkeys) 可能是必要的吗?恐怕我没有机会在真正的 MySQL 上进行测试 :-(
        • …或者,更一般地说:保存你转储的最后一个时间戳,然后WHERE timestamp > previous-timestamp
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-22
        • 2011-03-21
        • 2023-03-08
        • 2021-01-23
        • 2011-09-16
        • 1970-01-01
        • 2017-04-13
        相关资源
        最近更新 更多