【发布时间】: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 对于我当前的用例来说,一张表就足够了。但我也很想学习如何为所有桌子做这件事。 :) 谢谢!