我想使用
SELECT EXTRACT(EPOCH FROM TIMESTAMP '2019-06-01 00:00:00');
可作为独立查询:
postgres=# SELECT EXTRACT(EPOCH FROM TIMESTAMP '2019-06-01 00:00:00');
date_part
------------
1559347200
(1 row)
在这样的子查询中:
CREATE TABLE events_201906 PARTITION OF events
FOR VALUES FROM (SELECT EXTRACT(EPOCH FROM TIMESTAMP '2019-06-01 00:00:00')) TO (SELECT EXTRACT(EPOCH FROM TIMESTAMP '2019-07-01 00:00:00'));
但我不断得到:
ERROR: syntax error at or near "SELECT"
LINE 2: FOR VALUES FROM (SELECT EXTRACT(EPOCH FROM TIMESTAMP '20...
^
我在做什么错了?
答案 0 :(得分:1)
根据Postgres documentation for CREATE TABLE
:
partition_bound_spec 是:
IN ( { numeric_literal | string_literal | TRUE | FALSE | NULL } [, ...] ) | FROM ( { numeric_literal | string_literal | TRUE | FALSE | MINVALUE | MAXVALUE } [, ...] ) TO ( { numeric_literal | string_literal | TRUE | FALSE | MINVALUE | MAXVALUE } [, ...] ) | WITH ( MODULUS numeric_literal, REMAINDER numeric_literal )
因此它不能是子查询,必须是文字查询。
但是,如果需要,您可以动态执行分区语句,例如:
create or replace function create_partition() returns int as
$fn$
declare
p_from bigint;
p_to bigint;
query text;
begin
SELECT EXTRACT(EPOCH FROM TIMESTAMP '2019-06-01 00:00:00') into p_from;
SELECT EXTRACT(EPOCH FROM TIMESTAMP '2019-07-01 00:00:00') into p_to;
query := 'CREATE TABLE events_201906 PARTITION OF events
FOR VALUES FROM (' || p_from || ') TO (' || p_to || ');';
execute query;
return 1;
end;
$fn$ language plpgsql;
然后执行。当然,您可以通过接受分区名称和时间戳记的参数来使其更有用。