【问题标题】:SQL Group By and Order -- retrieve detail for most recent entries in tableSQL Group By and Order -- 检索表中最新条目的详细信息
【发布时间】:2021-11-11 21:02:29
【问题描述】:

我想创建一个 SQL 查询,返回每个 bot_id 的最新条目。

我当前的请求看起来像这样,但它总是返回第一个条目。 DESC 和 ASC 没有任何区别:

SELECT bot_id, id
FROM t_request_history
GROUP BY bot_id
ORDER BY request_time DESC

表格如下所示:


t_request_history

​​>
id bot_id request response error request_time
1 usr_e74ae42b-080c-48e0-9e6c a a 0 2021-09-16 23:37:10
2 usr_e74ae42b-080c-48e0-9e6c a a 1 2021-09-16 23:37:35
3 usr_e74ae42b-080c-48e0-9e6c a a 1 2021-09-16 23:43:20
4 delete 1 1 1 2021-09-16 23:44:21
5 delete 1 1 0 2021-09-16 23:44:32
6 delete 1 1 0 2021-09-16 23:44:41



想要的结果

bot_id id
delete 6
usr_e74ae42b-080c-48e0-9e6c 3

实际结果

bot_id id
delete 4
usr_e74ae42b-080c-48e0-9e6c 1

有什么办法可以使这个查询工作吗?

【问题讨论】:

    标签: sql group-by mariadb sql-order-by


    【解决方案1】:

    您的id 值似乎随着时间的推移而上升。也就是说,表中较新的条目看起来比旧条目具有更高的 id 值。如果这是真的,

    SELECT bot_id, MAX(id) id
    FROM t_request_history
    GROUP BY bot_id
    

    得到你想要的。

    如果id 的值不随时间上升,则必须使用子查询来查找每个 bot_id 的最新时间。

                     SELECT bot_id, MAX(request_time) request_time
                       FROM t_request_history
                      GROUP BY bot_id
    

    然后你像这样将该子查询加入到你的表中:

    SELECT a.bot_id, a.id
      FROM t_request_history a
      JOIN (
                        SELECT bot_id, MAX(request_time) request_time
                          FROM t_request_history
                         GROUP BY bot_id
           ) b   ON a.bot_id = b.bot_id
                AND a.request_time = b.request_time
    

    JOIN 的 ON 条件只选择表中时间最近的行。

    【讨论】:

      【解决方案2】:

      您可以使用窗口/分析函数来做到这一点

      SELECT distinct
       bot_id, MAX(request_time) OVER(PARTITION BY bot_id)
      FROM t_request_history
      ;
      

      SQLFiddle

      您还可以找到更多关于使用@MariaDB WindowFunction Max documentation的详细信息

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-30
        • 1970-01-01
        • 2010-10-09
        • 2023-02-06
        • 1970-01-01
        相关资源
        最近更新 更多