1

在这个例子中,我必须对从 2012-12-17 到 2012-10-30 的大量不相交的每日表格进行联合。这里的代码变得丑陋是片段:

CREATE table map 
with (appendonly=true, compresstype = quicklz)
AS
 SELECT * FROM final_map_12_17
    UNION ALL
 SELECT * FROM final_map_12_16
    UNION ALL
     SELECT * FROM final_map_12_15
    UNION ALL
     SELECT * FROM final_map_12_14
    UNION ALL
....
SELECT * FROM final_map_10_30;

我可以用序列或 PL/PGSQL 函数来做这种事情,而不是手动写出每个单独的选择吗?

4

3 回答 3

1

没有可以执行此操作的 SQL 函数。

我建议您将表格列表放在 Excel 中。然后输入一个公式,例如:

="select * from "&a1&" union all"

把这个公式抄下来。瞧!您几乎拥有视图定义。

将包含这些语句的列复制到 SQL 命令工具中。create view在顶部添加。去掉union all最后的。瞧。您可以轻松创建视图。

于 2013-01-22T19:39:26.647 回答
1

Have a think about redefining your list of tables as a partitioned table, with a single master table and multiple child tables. http://www.postgresql.org/docs/9.2/static/ddl-partitioning.html

Alternatively, maintain a view to union all the tables together, and when you add a new table to the schema add it to the view also.

于 2013-01-23T09:08:10.250 回答
1

You can loop over date range in plpgsql function like this:

create or replace function add_map(date_from date, date_to date)
returns void language plpgsql as $$
declare
    day date;
begin
    for day in 
        select generate_series(date_from, date_to, '1 day')
    loop
        execute 'insert into map select * from final_map_'|| 
            to_char(extract(month from day), '09')|| '_' || 
            to_char(extract(day from day), '09');
    end loop;
end; $$;

Calling the function:

-- create table map (....);
select add_map('2012-11-30', '2012-12-02');

is equivalent to:

insert into map select * from final_map_11_30;
insert into map select * from final_map_12_01;
insert into map select * from final_map_12_02;
于 2013-01-22T22:44:53.393 回答