具有多个父项的表的外键 CASCADE DELETE?
我对外键和 CASCADE 操作非常陌生,并且想知道以下情况:
假设我有两个完全不同的父表(HUMAN 和 ALIEN),数据完全不同。现在,我想做的是创建一个名为 SPACESHIP 的子表,因为人类和外星人都可以拥有宇宙飞船,并且 FK 指向 HUMAN 中的一行或 ALIEN 中的一行,希望如果我删除其中一个人类行或外星人行,它会级联删除各自父级拥有的相应宇宙飞船行。有没有好的方法可以使用 FK 和 CASCADE DELETE 来做到这一点?或者我应该在 HUMAN 和 ALIEN 中有一列名为 spaceship_id 的列,并手动/通过触发器处理太空飞船的删除?还有其他行动方案吗?
帮助!
I am very new to foreign keys and CASCADE operations, and am wondering about the following scenario:
Let's say I have two completely different parent tables (HUMAN and ALIEN) with completely different data. Now, what I want to do is create a child table named SPACESHIP, as both humans and aliens can own spaceships, with an FK that would point to either a row in HUMAN or a row in ALIEN, in the hopes that if I delete either a human row or an alien row, it would Cascade Delete the corresponding spaceship rows owned by the respective parent. Is there a good way to do this with FK's and CASCADE DELETE? Or should I just have a column in HUMAN and ALIEN called spaceship_id
and handle the delete of spaceships manually / via trigger? Some other course of action?
Help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可以通过添加一个超类型表(我们称之为
Being
)来解决,该表具有两个Human
和Alien
表作为子类型。然后FOREIGN KEY
约束将引用这个超类型表。超类型:
子类型:
和
Spaceship
表:This can be solved by adding a supertype table (lets call it
Being
) that has as subtypes the twoHuman
andAlien
tables. Then theFOREIGN KEY
constraint would reference this superype table.The supertype:
the subtypes:
and the
Spaceship
table:如果您使用 InnoDB 存储引擎,那么你可以使用外键,因为目前只有 InnoDB 支持它们。否则,您可以使用 触发器 或删除父记录和子记录使用一个查询,例如:
If you use InnoDB storage engine, then you can use foreign keys, because currently only InnoDB supports them. Otherwise you can use triggers or delete parent and child records using one query, e.g.: