[英]Check constraint with dynamic parameters
I am creating partition table with PostgreSQL. 我正在用PostgreSQL创建分区表。
CREATE TABLE tt_parent
(
id integer,
log_time timestamp with time zone,
server_id integer,
name text,
CONSTRAINT tt_parent_pkey PRIMARY KEY (id)
)
CREATE TABLE tt_1_2015_week42 (
CHECK ( server_id = 1 AND log_time >= (to_timestamp('2015-42', 'IYYY-IW')) AND log_time <= (to_timestamp('2015-42', 'IYYY-IW') + '6 days'::interval)
) INHERITS (tt_parent);
CREATE TABLE tt_1_2015_week43 (
CHECK ( server_id = 1 AND log_time >= (to_timestamp('2015-43', 'IYYY-IW')) AND log_time <= (to_timestamp('2015-43', 'IYYY-IW') + '6 days'::interval)
) INHERITS (tt_parent);
CREATE TABLE tt_1_2015_week44 (
CHECK ( server_id = 1 AND log_time >= (to_timestamp('2015-44', 'IYYY-IW')) AND log_time <= (to_timestamp('2015-44', 'IYYY-IW') + '6 days'::interval)
) INHERITS (tt_parent);
After creating the above child table when i fire below query then it scan all the child table. 创建完上面的子表后,当我在下面的查询中触发时,它将扫描所有子表。
EXPLAIN SELECT * FROM tt_parent
WHERE server_id = 1
AND (log_time >= '2015-10-12 00:00:00'::TIMESTAMP WITH TIME ZONE)
AND (log_time <= '2015-10-15 00:00:00'::TIMESTAMP WITH TIME ZONE);
From the above query, log_time in where clause is with week 42. So the query should scan only "tt_1_2015_week42" child table. 从上面的查询中,where子句中的log_time位于第42周。因此,该查询应仅扫描“ tt_1_2015_week42”子表。 Why above query scan all the 3 child tables ?
为什么上面的查询会扫描所有3个子表?
Check constraint with dynamic value does not work ? 用动态值检查约束不起作用? We can not use "to_timestamp" function inside Check constraint ?
我们不能在Check约束中使用“ to_timestamp”功能吗? How to modify the above child table check constraint so that query can scan only week 42 table.
如何修改上面的子表检查约束,以便查询只能扫描第42周的表。
1) Your check-conditions missing periods between two neighbour partitions. 1)您的检查条件缺少两个相邻分区之间的时间段。 For example, a gap:
例如,差距:
from: to_timestamp('2015-42', 'IYYY-IW') + '6 days'::interval --2015-10-18 00:00:00
to: to_timestamp('2015-43', 'IYYY-IW')) --2015-10-19 00:00:00
I would write: 我会写:
CHECK (
server_id = 1 AND
log_time >= '2015-10-12'::timestamptz AND
log_time < '2015-10-12'::timestamptz + interval '1 week' --'<' sign, not '<=' to avoid overlapping
)
2) To get what you want you need an option constraint_exclusion set to partition
(this should be a default value). 2)要获得所需的内容,您需要一个选项constraint_exclusion设置为
partition
(这应该是默认值)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.