sql - 在一个非常大的表中为每个组有效地选择最新的行?

标签 sql amazon-redshift query-optimization greatest-n-per-group

我有(例如)一张 table Users (user_id, status, timestamp, ...) .
我还有一张 table SpecialUsers (user_id, ...) .
我需要显示每个特殊用户的最新状态。
问题在于Users表是 非常非常大 (超过 50 十亿 行)。例如this question中的大多数解决方案只是挂起或出现“磁盘已满”错误。SpecialUsers表要小得多 - “只有” 600K 行。SELECT DISTINCT ON()不支持。在 Amazon RedShift 上工作。
编辑 :每个请求查看失败的尝试 - 导致磁盘已满错误的其中一个是这样的:

with users_with_status (user_id, status, timestamp)
as (
        select su.user_id, u.instance_type, u.timestamp
        from specialusers su
        join users u on su.user_id = u.user_id
)
select l.instance_id, l.instance_type
from users_with_status l
left outer join users_with_status r
     on l.user_id = r.user_id and l.timestamp < r.timestamp
where r.timestamp is null;
我知道我自己加入了一个错误表,但希望第一次加入小表会减少处理的行数。
无论如何,似乎窗口函数是这里的解决方案。

最佳答案

也许是 join使用窗口函数将起作用:

select su.*
from (select s.user_id, u.status, u.timestamp,
             max(u.timestamp) over (partition by s.user_id) as max_timestamp
      from specialusers s join
           users u
           on s.user_id = u.user_id
     ) su
where timestamp = max_timestamp;
这特别使用 max()而不是 row_number()猜测它可能会使用更少的资源。

关于sql - 在一个非常大的表中为每个组有效地选择最新的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68349039/

相关文章:

MySQL 对两个表字段求和并更新

postgresql - 为什么 "||"在 PostgreSQL/Redshift 中用作字符串连接

mysql - 如何编写用于将数据从 MySQL 加载到 Redshift 的 Luigi 工作流?

mysql - 针对 max、count 优化 MySQL InnoDB 查询

mysql - 亿级表优化查询

mysql - 将一个表中的多个列连接到另一个表中的单个列

php - mysql_escape_string 整个帖子数组?

SQL:在A列最小的情况下快速获取B列的值

node.js - Redshift - node-orm-2 的自动增量 ID 不支持类型 "serial"

mysql - 优化MySQL中的UPDATE语句