【问题标题】:Redshift: Query all tables with a common columnRedshift:查询所有具有公共列的表
【发布时间】:2020-08-04 10:08:14
【问题描述】:

我正在尝试在 Redshift 中创建一个视图,以使我们能够查看每个表中的最新数据。 我们有更新各种时间表的数据集,每个表都有一个“更新”列,其中包含上次更新行的日期戳。

我想要实现的是底部的视图(来自这两个示例表):

other.bigtable
+-----+--------+------------------+
| id  |  stat  |     updated      |
+-----+--------+------------------+
| A2  | rgerhg | 03/05/2020 05:00 |
| F5  | bdfb   | 03/05/2020 05:00 |
| GF5 | bb     | 03/05/2020 05:00 |
+-----+--------+------------------+
default.test
+----+------+------------------+
| id | name |     updated      |
+----+------+------------------+
|  1 | A    | 02/02/2008 00:00 |
|  2 | B    | 02/02/2008 00:00 |
|  3 | C    | 02/02/2008 00:00 |
|  4 | F    | 02/02/2008 00:00 |
|  5 | T    | 02/02/2010 00:00 |
+----+------+------------------+
default.view_updates
+---------+------------+------------------+
| schema  | table_name |    max_update    |
+---------+------------+------------------+
| default | test       | 02/02/2010 00:00 |
| other   | big_table  | 03/05/2020 05:00 |
+---------+------------+------------------+

到目前为止,我正在获取表格和架构,但不知道从哪里开始日期。 Redshift 似乎有点受限。

编辑:

利用从网上窃取的一些代码,我希望用它来为额外的列创建表:

    select t.table_schema,
        t.table_name
    from information_schema.tables t
    inner join information_schema.columns c 
        on c.table_name = t.table_name 
        and c.table_schema = t.table_schema
    where c.column_name = 'updated'
        and t.table_schema not in ('information_schema', 'pg_catalog')
        and t.table_type = 'BASE TABLE'
    order by t.table_schema;

[来源:https://dataedo.com/kb/query/amazon-redshift/find-tables-with-specific-column-name]

【问题讨论】:

    标签: amazon-redshift


    【解决方案1】:

    您可以从每个表中选择最近的日期并将其合并在一起(如果您愿意,可以放入视图中)。

    Select * from (select top 1 'test', update from test order by updated desc) 联合所有 Select * from (select top 1 'big_table', updated from big_table order by updated desc);

    您可以有一个长长的“联合所有”列表,直到某个限制。这会将表格硬编码到视图中 - 我认为这就是您要查找的内容。

    【讨论】:

    • 嗨,比尔,谢谢。这就是我想我可能必须做的事情。我希望使用诸如此类的代码来做一些更动态的事情,以获取所有具有该列的表和模式。 (将代码添加到原始帖子中,因为无法在 cmets 中对其进行格式化)
    • 通过“动态”,您要发出的 SQL 将随着数据库中表的变化而变化。这将您的数据请求带入了一个更加程序化的领域。我希望这可以用 python UDF 来完成,但这不是我的强项。如果我有这个问题,我会在 Redshift 之外寻找 AWS 云来运行程序方面 - 即 Lambda。 Lambda 函数可以找到包含该列的表,并在此列表中循环查找最新日期。如果您愿意,它可以将其存储回表中。只需让 Lambda 使用单个事务来确保数据一致性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2021-07-29
    相关资源
    最近更新 更多