How do you deal with m..n relationships in a relational database?

前端 未结 10 1098
醉梦人生
醉梦人生 2020-12-14 18:48

Let\'s look at an example - books. A book can have 1..n authors. An author can have 1..m books. What is a good way to represent all of the authors of a book?

I came

10条回答
  •  盖世英雄少女心
    2020-12-14 19:28

    For 1..n relationship (author has many books, author has many aliases):

    1. Put a foreign key author_id in Books pointing at author.
    2. Create a new table, author_aliases, to hold the aliases information.
    3. Put a foreign key alias_id in Books pointing at alias (nullable if author details are defaul).
    4. Put author_id foreign key in author_aliases.

    If you wish, you can use intermediary tables to link authors and books, but with a 1..n mapping I don't think this is necessary.

    For an n..m relationship (author has many books, book has many authors):

    You would have to use an intermediary join table (author_id, alias_id, book_id) instead of foreign keys in the book table. You will want to keep the foreign key from aliases to author (for easy lookup of author aliases without having to go via all their books).

    You can argue that in terms of scalability in the future this is a better way to start off as well, even if the initial specification says something is a 1..n relationship. You will find that specifications (or question) as given often are inadequate, so you will want to design in the general manner for when the specifications change or are clarified.

提交回复
热议问题