我的分区表 SELECT 查询包括所有分区表,即使检查到位并且 constraint_exclusion = on。
插入触发器工作正常,新行被插入到正确的表中。然而,无论我的 WHERE 子句如何,SELECT 都会在所有表上运行。
这是我的配置:
constraint_exclusion = on (both in postgresql.conf and also tried with "ALTER DATABASE bigtable SET constraint_exclusion=on;")
主表:
CREATE TABLE bigtable (
id bigserial NOT NULL,
userid integer NOT NULL,
inserttime timestamp with time zone NOT NULL DEFAULT now()
)
子表1:
CREATE TABLE bigtable_2013_11 (CHECK ( inserttime >= DATE '2013-11-01' AND inserttime < DATE '2013-12-01' )) INHERITS (bigtable);
子表2:
CREATE TABLE bigtable_2013_12 (CHECK ( inserttime >= DATE '2013-12-01' AND inserttime < DATE '2014-01-01' )) INHERITS (bigtable);
存储过程:
CREATE OR REPLACE FUNCTION bigtable_insert_function()
RETURNS TRIGGER AS $$
BEGIN
IF ( NEW.inserttime >= DATE '2013-11-01' AND NEW.inserttime < DATE '2013-11-01' ) THEN
INSERT INTO bigtable_2013_11 VALUES (NEW.*);
ELSEIF (NEW.inserttime >= DATE '2013-12-01' AND NEW.inserttime < DATE '2014-01-01' ) THEN
INSERT INTO bigtable_2013_12 VALUES (NEW.*);
ELSE
RAISE EXCEPTION 'Bigtable insert date is out of range!';
END IF;
RETURN NULL;
END;
$$
LANGUAGE plpgsql;
扳机:
CREATE TRIGGER bigtable_insert_trigger BEFORE INSERT ON bigtable FOR EACH ROW EXECUTE PROCEDURE bigtable_insert_function();
这几乎是教科书的设置。插入工作正常:
INSERT INTO bigtable (userid, inserttime) VALUES ('1', now());
上面的插入导致新行仅正确插入到“bigtable_2013_11”中。
但是我不能让 SELECT 排除不相关的表。所有 SELECT 总是在所有表上运行。当使用以下 SELECT 查询时,我希望 bigtable_2013_12 被排除:
SELECT * FROM bigtable WHERE inserttime >= DATE '2013-11-01'::date AND inserttime < '2013-12-01'::date;
SELECT * FROM bigtable WHERE EXTRACT(MONTH FROM inserttime) = 11 AND EXTRACT (YEAR FROM inserttime) = 2013;
然而结果总是这样:
"Result (cost=0.00..68.90 rows=17 width=20)"
" -> Append (cost=0.00..68.90 rows=17 width=20)"
" -> Seq Scan on bigtable (cost=0.00..0.00 rows=1 width=20)"
" Filter: ((inserttime >= '2013-11-02'::date) AND (inserttime < '2013-11-30'::date))"
" -> Seq Scan on bigtable_2013_11 bigtable (cost=0.00..34.45 rows=8 width=20)"
" Filter: ((inserttime >= '2013-11-02'::date) AND (inserttime < '2013-11-30'::date))"
" -> Seq Scan on bigtable_2013_12 bigtable (cost=0.00..34.45 rows=8 width=20)"
" Filter: ((inserttime >= '2013-11-02'::date) AND (inserttime < '2013-11-30'::date))"
为什么我的支票没有生效?我没主意了。一切似乎都设置正确。我错过了什么吗?任何帮助将不胜感激。