【问题标题】:Selecting the most recent entry (row) using datetime column使用日期时间列选择最近的条目(行)
【发布时间】:2016-11-30 21:50:44
【问题描述】:

我有一张如下所示的表格:

table_name  |  event_time           |  row_count  |  num_of_times_observed
test        |  2016-11-30 15:33:47  |  200        |  0
test        |  2016-11-30 16:03:03  |  400        |  0
test11      |  2016-11-30 15:33:34  |  300        |  0
test11      |  2016-11-30 15:57:49  |  400        |  0

我想在event_time给定一个表名(或者更一般地说,每个不同的表名)中找到具有最新值的行。例如,如果我们要查找table_name, 'test11' 的最近时间,我们会得到这样的结果:

table_name  |  event_time           |  row_count  |  num_of_times_observed
test11      |  2016-11-30 15:57:49  |  400        |  0

我可以想到两种标准(初学者)方法来实现这一目标:

SELECT table_name -- Approach#1
    ,event_time
    ,row_count
    ,num_of_times_observed
FROM my_table AS u
WHERE table_name = 'test11'
ORDER BY event_time DESC LIMIT 1

或者这个:

SELECT table_name -- Approach#2
    ,event_time
    ,row_count
    ,num_of_times_observed
FROM (
    SELECT *
    FROM my_table
    WHERE table_name = 'test11'
    ) AS u -- I really don't need to filter by table_name here, but I hope it will improve the performance by just a little (especially if there are >100K rows for 'test11')?
INNER JOIN (
    SELECT table_name
        ,max(event_time) AS event_time
    FROM my_table
    GROUP BY table_name
    HAVING table_name = 'test11'
    ) AS q ON u.table_name = q.table_name
    AND u.event_time = q.event_time

假设my_table 中有大约 1 亿行,我觉得上述方法可能不是很有效(优化)。我环顾 StackOverflow 寻找可能的答案,发现诸如 this one 之类的更高级的答案。我想知道是否有更好(有效)的方法来查询所需的结果。

非常感谢您的回答和建议!

【问题讨论】:

  • 请用您正在使用的数据库标记您的问题。
  • 您想要所有表或仅一张表的最新事件列表?
  • @GordonLinoff 谢谢。用我使用的数据库标记。 :)
  • @mcNets 对于我当前的用例来说,一张表就足够了。但我也很想学习如何为所有桌子做这件事。 :) 谢谢!

标签: sql vertica


【解决方案1】:

您的第一种方法是最好的方法。

您希望在my_table(table_name, event_time) 上建立索引。有些数据库允许您在创建索引时在列上指定desc

【讨论】:

    【解决方案2】:

    你也可以用

    每张桌子

    select * from my_table 
    where ( table_name, event_time) in ( select table_name, max(event_time) 
                                    from my_table
                                        group by table_name )
    

    或者如果您使用的数据库不允许使用元组,您可以使用
    加入

     select * from my_table t1 
     INNER JOIN (  
       select table_name, max(event_time) max_event 
       from my_table
       group by table_name ) t2 on t2.table_name = t1.table_name 
                                       and t2.max_event = t1.event_time
    

    绝对值

    select * from my_table as  u
    where event_time in ( select max(event_time )  from my_table)
    

    【讨论】:

    • 对每个表的查询返回语法错误。我认为 SQL 中不允许在 (select ...) 中使用 `where (table_name, event_time)。
    • 您使用的是哪个数据库?
    • 无论如何我已经更新了最终不使用元组的db的答案..
    • 谢谢!我使用 Vertica。但似乎INNER JOIN 和标准ORDER BY 是要走的路。
    猜你喜欢
    • 2013-08-10
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 2014-09-17
    • 2017-03-19
    相关资源
    最近更新 更多