[英]Postgres single foreign key to different tables
我有一些postgres表:
Component Component_A Component_B
----------- ------------ ------------
id id id
component_type type type
component_id foo_col bar_col
我希望Component
能够引用Component_A
或Component_B
,这取决于component_type
和component_id
的组合。 Component_A
和Component_B
具有不同的结构,因此不能将它们存储在同一表中。 从某种意义上说, Component
与Component_A
和Component_B
都是1比1。
在Postgres中对此建模的最佳方法是什么?
如果我对您的理解正确,我会在Component_A中放入一个外键作为ID,并在Component中引用component_type和component_id。 与Component_B相同。 如果将ON DELETE CASCADE放在这两个外键中,则每当删除一个Component时,它们对应的Component_A或Component_B都会被删除,从而使数据库中没有这些表上的孤立记录。
如果您正在寻找另一种方法(删除Component_A中的记录并删除相应的Component),则不确定是否可以通过外键来完成,但是您可以通过在Component_A中使用TRIGGER进行DELETE来实现和负责删除与组件相关的记录的Component_B。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.