[英]Postgres cascade delete on non-unique column
I have a table like this: 我有一张这样的桌子:
id | group_id | parent_group
---+----------+-------------
1 | 1 | null
2 | 1 | null
3 | 2 | 1
4 | 2 | 1
Is it possible to add a constraint such that a row is automatically deleted when there is no row with a group_id
equal to the row's parent_group
? 是否可以添加约束,以便在没有group_id
等于该行的parent_group
的行时自动删除该行? For example, if I delete rows 1 and 2, I want rows 3 and 4 to be deleted automatically because there are no more rows with group_id
1. 例如,如果我删除第1行和第2行,我希望自动删除第3行和第4行,因为没有更多具有group_id
1的行。
The answer that clemens posted led me to the following solution. clemens发布的答案使我想到了以下解决方案。 I'm not very familiar with triggers though; 我对触发器不是很熟悉。 could there be any problems with this and is there a better way to do it? 可能有任何问题吗,还有更好的方法吗?
CREATE OR REPLACE FUNCTION on_group_deleted() RETURNS TRIGGER AS $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM my_table WHERE group_id = OLD.group_id) THEN
DELETE FROM my_table WHERE parent_group = OLD.group_id;
END IF;
RETURN OLD;
END;
$$ LANGUAGE PLPGSQL;
CREATE TRIGGER my_table_delete_trigger AFTER DELETE ON my_table
FOR EACH ROW
EXECUTE PROCEDURE on_group_deleted();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.