我正在考慮使用觸發器來維護鏈接表。但是,由於違反外鍵約束,我的初始方法失敗。有沒有辦法解決這個問題,而不禁用約束?使用觸發器來維護鏈接表
CREATE TABLE foo (
id SERIAL PRIMARY KEY,
data TEXT
);
CREATE TABLE bar (
id SERIAL PRIMARY KEY,
data TEXT
);
CREATE TABLE foo_bar_link (
foo_id INT NOT NULL REFERENCES foo(id),
bar_id INT NOT NULL REFERENCES bar(id),
UNIQUE (foo_id, bar_id)
);
CREATE OR REPLACE FUNCTION maintain_link()
RETURNS TRIGGER AS
$maintain_link$
DECLARE
bar_id INT;
BEGIN
INSERT INTO bar (data) VALUES ('not_important_for_this_example_bar_data') RETURNING id INTO bar_id;
INSERT INTO foo_bar_link (foo_id, bar_id) VALUES (NEW.id, bar_id);
RETURN NEW;
END;
$maintain_link$
LANGUAGE plpgsql;
CREATE TRIGGER maintain_link BEFORE INSERT ON foo
FOR EACH ROW EXECUTE PROCEDURE maintain_link();
這裏是sqlfiddle。
您如何知道鏈接到新foo記錄的條形記錄? –
它來自'INSERT INTO bar'子句的'RETURNING ID INTO bar_id'。 –