簡體   English   中英

Postgres單個外鍵到不同的表

[英]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_AComponent_B ,這取決於component_typecomponent_id的組合。 Component_AComponent_B具有不同的結構,因此不能將它們存儲在同一表中。 從某種意義上說, ComponentComponent_AComponent_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM