如何解决这个触发器递归心灵打击?

时间:2017-01-15 16:00:56

标签: sql postgresql triggers

我们有3个表:T1,T2,T3,其中一个只有一列(一个int)。一切都是空的。 我们有6个触发器:

T1:

CREATE TRIGGER D1_1
BEFORE INSERT ON T1
FOR EACH ROW WHEN (SELECT COUNT(*) FROM T2) < 1
INSERT INTO T2 VALUES (6);


CREATE TRIGGER D1_2
AFTER INSERT ON T1
FOR EACH ROW WHEN (SELECT COUNT(*) FROM T2) < 2
INSERT INTO T3 VALUES (25);

T2:

CREATE TRIGGER D2_1
BEFORE INSERT ON T2
FOR EACH ROW WHEN (SELECT COUNT(*) FROM T3) < 1
INSERT INTO T3 VALUES (15);


CREATE TRIGGER D2_2
AFTER INSERT ON T2
FOR EACH ROW WHEN (SELECT COUNT(*) FROM T1) < 10
INSERT INTO T1 VALUES (28);

T3:

CREATE TRIGGER D3_1
BEFORE INSERT ON T3
FOR EACH ROW WHEN (SELECT COUNT(*) FROM T2) > 10
INSERT INTO T1 VALUES (21);


CREATE TRIGGER D3_2
AFTER INSERT ON T3
FOR EACH ROW WHEN (SELECT COUNT(*) FROM T3) < 2
INSERT INTO T2 VALUES (32);

然后我们这样做:

INSERT INTO T1 VALUES (0);

附加什么,插入顺序是什么?

但我不知道插入BEFORE和AFTER之后的优先级。 例如,我认为程序的开头是: T1之前 - &gt;插入T2所以 - &gt;在T2之前 - &gt;插入T3所以 - &gt;在T3之前(没有匹配条件)所以插入T2 ......?

1 个答案:

答案 0 :(得分:0)

执行顺序如下:

insert into T1 values (0)
    trigger d1_1
    T2 has 0 records
    insert into T2 values (6)
        trigger d2_1
        T3 has 0 records
        insert into T3 values (15)
            trigger d3_1
            T2 has 0 records
            15 is now inserted into T3
            trigger d3_2
            T3 has 1 records
            insert into T2 values (32)
                trigger d2_1
                T3 has 1 records
                32 is now inserted into T2
                trigger d2_2
                T1 has 0 records
                insert into T1 values (28)
                    trigger d1_1
                    T2 has 1 records
                    28 is now inserted into T1
                    trigger d1_2
                    T2 has 1 records
                    insert into T3 values (25)
                        trigger d3_1
                        T2 has 1 records
                        25 is now inserted into T3
                        trigger d3_2
                        T3 has 2 records
        6 is now inserted into T2
        trigger d2_2
        T1 has 1 records
        insert into T1 values (28)
            trigger d1_1
            T2 has 2 records
            28 is now inserted into T1
            trigger d1_2
            T2 has 2 records
    0 is now inserted into T1
    trigger d1_2
    T2 has 2 records
Done.

最后:

  • T1有28,28,0
  • T2有32,6
  • T3有15,25