【问题标题】:Get last update values from MySQL table从 MySQL 表中获取最后更新值
【发布时间】:2013-03-01 10:12:30
【问题描述】:

我有一个具有以下结构和数据的 mysql 表。我想在任何 id 上显示最后插入的记录。

id    lc_counter       lc_timestamp
1     15               2013-03-01 11:54:43
1     13               2013-03-01 11:48:56
10    7                2013-03-01 11:54:43
10    5                2013-03-01 11:48:56
100   5                2013-03-01 11:54:43
100   3                2013-03-01 11:54:43


SELECT inv_id, lc_counter, lc_timestamp 
FROM link_counter 
group by inv_id
order by inv_id asc, lc_timestamp desc

我想得到这个结果:

id    lc_counter       lc_timestamp
1     15               2013-03-01 11:54:43
10    7                2013-03-01 11:54:43
100   5                2013-03-01 11:54:43

【问题讨论】:

    标签: mysql group-by


    【解决方案1】:
    Select link_counter.lc_counter, MAX(link_counter.lc_timestamp)
     from link_counter group by link_counter.id
    

    【讨论】:

      【解决方案2】:
      SELECT
        inv_id, lc_counter, lc_timestamp
      FROM
        link_counter A
      WHERE
        lc_counter >= ALL(
          SELECT
            lc_counter
          FROM
            link_counter B
          WHERE
            B.inv_id = A.inv_id
        )
      ORDER BY
        1
      

      有一段时间没有这样做了,但应该可以。

      【讨论】:

        【解决方案3】:

        如果对于特定的 id 没有 2 条相同的 lc_timestamp 记录,以下将为您提供所需的确切结果。

        select lc.id, lc.lc_counter, lc.lc_timestamp from link_counter lc inner join
         (select id, max(lc_timestamp) as lc_timestamp from link_counter group by id) as lc2 
         on lc.id = lc2.id and lc.lc_timestamp = lc2.lc_timestamp order by lc.id asc, lc.lc_timestamp desc;;
        

        group by 本身不返回匹配的lc_counter。所以,需要手动匹配。请参阅此fiddle

        【讨论】:

        • Dipesh Parmer 和 aaaaaa123456789 的答案将返回此数据集的预期结果。但如果数据发生变化,它可能会返回错误的值(不要低估他们的支持)。检查小提琴中更改的数据集(lc_timestamp top 2 values swapped)。这是我今天能做的最好的事情。进一步了解 group by 的工作原理。这个question有点描述。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-17
        • 2013-01-25
        • 2010-11-26
        • 2017-09-03
        • 2019-09-26
        • 1970-01-01
        相关资源
        最近更新 更多