[英]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.