Circular dependencies in foreign keys: use it or avoid it?

自作多情 提交于 2019-12-03 07:24:28

The only time you should need a circular reference is when you are creating a hierarchical structure, such as an organizational tree.

Table Employees
   EmployeeID   <----------|
   SupervisorEmployeeID ---|

From a data modelling perspective there is nothing fundamentally "wrong" with a circualr dependency. It doesn't mean the model is wrong.

Unfortunately most SQL DBMSs cannot effectively implement such constraints because they don't support multiple table updates. Usually the only way around this is to suspend one or more constraints temporarily (for instance using a "deferrable" foreign key or similar features) or by altering the model to make some part of the constraint optional (putting one of the referencing columns into a new table). This is just a workaround for a nasty limitation of SQL however, it doesn't mean you did anything wrong to start with.

You have to model the data you have. If there's a circular relationship in the data (e.g. each photo belongs to a folder; but each folder has one cover photo) then it's correct to model that as a circular relationship in the database.

I only had this situation once when using Oracle, so I didn't get a chance to check out how to implement such a relationship on other databases. But for Oracle you can read my article here:

http://www.databasesandlife.com/circular-dependencies-on-foreign-key-constraints-oracle/

Yes, cyclical dependencies in databases are a good excuse to rethink the design.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!