Many-to-Many relationships needing an associate table

时间秒杀一切 提交于 2019-12-02 07:14:08

You can't make many to many relations any other way using relational databases. Ie, if you have a table called "person", you can't create a column "friends" and expect to put many friends' user ids in there. You have to make a separate table to hold the relation itself.

In relational databases all relationships are represented in only one way: as relations (relations correspond to tables in SQL). A relation with two attributes, such as R{A,B}, represents a binary relationship between A and B. That relationship could be one-to-many or many-to-many for example.

If the relationship represented by R{A,B} is many-to-many that implies that neither A or B are candidate keys (because if either was unique then obviously only ONE tuple for each value of that attribute would be permitted). That means that the principle of Third Normal Form requires any attributes dependent on A or B to go in other tables. The reason for this is that non-key dependencies (attributes dependent on A or B) are a form of redundancy and can cause anomalies and incorrect results.

So it's not that "many-to-many relationships" are represented any differently to other relationships. It's just that normalization often leads to a common pattern with tables with compound keys and no other non-key attributes. Some people like to call that pattern an Association table - although personally I don't find that terminology very helpful.

If you don't create a third table, there is simply nowhere to store the relations.

With a one-to-one or one-to-many relation, you can store the relation in one of the tables. With a many-to-many relation you have to store the relations separately. (Well, theoretically you could store it as a comma separated list of identities in both tables, but that would be a nightmare to use and to maintain.)

Wikipedia describes it too. Just take a look: http://en.wikipedia.org/wiki/Many-to-many_(data_model)

If you still don't believe that many-to-many do realy need a third table, just try the Authors/Books examble (as described in the wikipedia article) with only two normalized tables.

It would not flexible if DB-Server could create 3rd table for you. If there will be a solution like that, you wouldn't have much influence to

  • change relation behavour

  • store other association information in assoc. table

  • performance enhancements

  • storage enhancements

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