如何级联从子表到父表的删除?

编程入门 行业动态 更新时间:2024-10-28 14:28:46
本文介绍了如何级联从子表到父表的删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我准备了演示问题的小提琴 。

I prepared a fiddle which demonstrates the problem.

CREATE TABLE parent ( parent_id integer primary key ); CREATE TABLE child ( child_name TEXT primary key, parent_id integer REFERENCES parent (parent_id) ON DELETE CASCADE ); INSERT INTO parent VALUES (1); INSERT INTO child VALUES ('michael',1), ('vanessa', 1);

我想要一种在删除子记录时将CASCADE删除到父记录的方法。 br> 例如:

I want a way for the delete to CASCADE to the parent record when a child record is deleted. For example:

DELETE FROM child WHERE child_name='michael';

这应该级联到父表并删除记录。

This should cascade to the parent table and remove the record.

推荐答案

外键仅在另一个方向起作用:级联从父级到子级删除,因此当父级(引用)记录为

Foreign keys only work in the other direction: cascade deletes from parent to child, so when the parent (referenced) record is deleted, any child (referencing) records are also deleted.

如果是1:1关系,则可以创建双向外键关系,其中一侧是最初可延期,并且双方都是级联的。

If it's a 1:1 relationship you can create a bi-directional foreign key relationship, where one side is DEFERRABLE INITIALLY DEFERRED, and both sides are cascade.

否则,您需要将 ON子表上的DELETE ... FOR EACH ROW 触发器,如果​​没有剩余子级,则删除父行。并发 INSERT 可能会导致竞争状况;您需要 SELECT ... FOR UPDATE 父记录,然后检查其他子记录。插入时的外键检查在引用的(父)记录上使用 FOR SHARE 锁定,这样应该可以防止出现任何竞争情况。

Otherwise, you will want an ON DELETE ... FOR EACH ROW trigger on the child table that removes the parent row if there are no remaining children. It's potentially prone to race conditions with concurrent INSERTs; you'll need to SELECT ... FOR UPDATE the parent record, then check for other child records. Foreign key checks on insert take a FOR SHARE lock on the referenced (parent) record, so that should prevent any race condition.

更多推荐

如何级联从子表到父表的删除?

本文发布于:2023-10-16 05:08:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1496589.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:级联   从子   表到父表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!