2015-11-12 84 views
2

雖然運行在PostgreSQL 9.4以下簡單的規則:如何編寫嵌套的PostgreSQL規則?

create table a1 (id int); 
create table a2 (id int); 
create table a3 (id int); 
create view a0 as select * from a1; 

insert into a1 values (1), (2), (3); 
insert into a2 select * from a1; 
insert into a3 select * from a1; 

Create or replace rule a0_delete as 
on delete to a0 do instead (
    delete from a1 where id = old.id; 
    delete from a2 where id = old.id; 
    delete from a3 where id = old.id; 
    select a1.id, a2.id, a3.id 
    from a1 
    left join a2 using(id) 
    left join a3 using(id); 
); 

delete from a0 where id = 2; 

我不能讓後第一次運行的任何行動,我不知道爲什麼。 雖然文檔http://www.postgresql.org/docs/9.4/static/rules-update.html指定它是可能的,但我找不到任何地方有多個動作的例子。

有沒有人有任何想法?

+0

不合格的'從計數器中刪除;'對我沒有意義。 2)你有沒有嘗試過一個'返回'鏈式查詢? – wildplasser

+0

我實際上有另一個查詢作爲第二個動作,做更復雜的事情。當它不起作用時,我嘗試了簡單的查詢,比如INSERT INTO table(id)values(1);''我現在對第二個動作沒有興趣,但是爲什麼它不運行。 – Tudor

回答

1

多命令規則完美無缺地工作。你可以試試這個腳本:

create table a1 (id int); 
create table a2 (id int); 
create table a3 (id int); 

insert into a1 values (1), (2), (3); 
insert into a2 select * from a1; 
insert into a3 select * from a1; 

create or replace rule a1_delete as 
on delete to a1 do instead (
    insert into a1 values (old.id* 2); 
    delete from a2 where id = old.id; 
    delete from a3 where id = old.id; 
    select a1.id, a2.id, a3.id 
    from a1 
    left join a2 using(id) 
    left join a3 using(id); 
); 

delete from a1 where id = 2; 

得到預期的結果:

CREATE TABLE 
CREATE TABLE 
CREATE TABLE 
INSERT 0 3 
INSERT 0 3 
INSERT 0 3 
CREATE RULE 
id | id | id 
----+----+---- 
    1 | 1 | 1 
    2 | | 
    3 | 3 | 3 
    4 | | 
(4 rows) 

DELETE 1 

你應該尋找一個邏輯錯誤在規則的第二個命令。

+0

根據你的回答,我發現問題只發生在視圖上。它不應該,對吧?我已經更新了這個問題來反映這一點。謝謝! – Tudor