Many-to-Many Relationship between two tables in two different databases

…衆ロ難τιáo~ 提交于 2020-01-16 01:36:19

问题


As mentioned in the title, is it possible to create many-to-many relationship between two tables that belong to two different databases? If yes, how can i perform that with PostgreSQL?


回答1:


The standard way of using foreign key constraints to enforce referential integrity is only possible within the same database - not db cluster. But you can operate across multiple schemas in the same database.

Other than that, you can create tables just the same way. And even join tables dynamically among remote databases using dblink or FDW. Referential integrity cannot be guaranteed across databases by the RDBMS, though.
Does not matter much whether the other DB is on the same physical machine or even in the same DB cluster - that just makes the connection faster and more secure.

Or you can replicate data to a common database and add standard constraints there.




回答2:


It should be possible, but as has been stated you cannot expect much in the way of referential integrity.

If you follow the standard design pattern of using a linking table, you can generate a sort of M2M relationship.

DB1.dbo.Users has the USER_ID primary key DB2.dbo.Tasks has the TASK_ID primary key

you could create a table on either DB1 or DB2 that is UsersToTasks

DB1.dbo.UsersToTasks
USER_ID - KEY
TASK_ID - KEY

This way, a unique pairing of USER_IDs and TASK_IDs are used as a key in that table. The only thing is you cannot create a foreign key to the other table.

As a pseudo workaround, you could write a trigger on DB2.dbo.Task that would write the TASK_ID to DB1.dbo.TASK_IDS and link that as the foreign key on the linking table above. I'm not sure, but you could also potentially create a delete trigger that would remove the TASK_ID as well.

http://solaimurugan.blogspot.com/2010/08/cross-database-triggers-in-postgresql.html



来源:https://stackoverflow.com/questions/28598146/many-to-many-relationship-between-two-tables-in-two-different-databases

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