【问题标题】:Selecting all records in all tables of the Public Schema in PostgreSQL选择 PostgreSQL 中公共模式的所有表中的所有记录
【发布时间】:2022-12-11 07:52:02
【问题描述】:

我的 PostgreSQL 数据库的公共模式中有几个表。这些表名为“projects_2019”、“projects_2020”、“projects_2021”等,并且具有相同的列。这个想法是每年都会添加一张新桌子。

我想选择名称包含“projects_”的所有表中的所有记录,如果不命名每个表名我怎么能这样做(因为我不知道将来会有多少)?

这是我到目前为止所拥有的:

WITH t as
    (SELECT * FROM information_schema.tables WHERE table_schema = 'public' and table_name ~ 'projects_')
SELECT * FROM t

【问题讨论】:

  • 您的查询充其量只会为您提供表的名称。然后,您需要以 select * from <table1> union all select ... 的形式动态构建查询,然后执行生成的查询。也许更好的解决方案是按年构建 partitioned table 分区。

标签: postgresql


【解决方案1】:

您可以使用动态 SQL 和 information_schema 来完成。例如:

-- Sample Data
CREATE TABLE table1 (
    id int4 NULL,
    caption text NULL
); 

CREATE TABLE table2 (
    id int4 NULL,
    caption text NULL
); 

CREATE TABLE table3 (
    id int4 NULL,
    caption text NULL
); 

CREATE TABLE table4 (
    id int4 NULL,
    caption text NULL
); 

INSERT INTO table1 (id, caption) VALUES (1, 'text1');
INSERT INTO table2 (id, caption) VALUES (2, 'text2');
INSERT INTO table3 (id, caption) VALUES (3, 'text3');
INSERT INTO table4 (id, caption) VALUES (4, 'text4');

-- create function sample: 

CREATE OR REPLACE FUNCTION select_tables()
 RETURNS table(id integer, caption text)
 LANGUAGE plpgsql
AS $function$
declare 
    v_sql text;
    v_union text;
begin
    
    SELECT string_agg('select * from ' || table_schema || '.' || table_name, ' union all ')
    into v_sql
    FROM information_schema.tables WHERE table_schema = 'public' and table_name ~ 'table';

    return query 
    execute v_sql; 
    
end ;
$function$
;

-- selecting data: 
select * from select_tables()

-- Result: 
id  caption
1   text1
2   text2
3   text3
4   text4

【讨论】:

    猜你喜欢
    • 2013-12-12
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 2018-12-15
    • 2013-04-17
    • 2023-02-22
    相关资源
    最近更新 更多