one to many relationship in database - design concept

前端 未结 5 1176
日久生厌
日久生厌 2020-12-30 11:46

A one to many relationship between two tables should be implemented with two or three tables? For example should we have:

author(id,otherAttributtes)
books(i         


        
5条回答
  •  别那么骄傲
    2020-12-30 12:43

    The first example shows a one to many relationship, while the second shows a many to many relationship.

    Example lets say we use the first example

    Author
    AuthorID
    
    Book
    BookID
    AuthorID
    

    How would you represent that both Jane and Jon wrote the book "Stackoverflow for fun"? In this relationship table you cannot, you have expressed that one author can write many books. So either Jane wrote it or Jon wrote it. If only one of them wrote the books you could use this relationship type. However, if you want to show that both wrote this book you need a many to many relationship.

    Now using this same analogy of Jane and Jon you can represent both authors to this one book using your second example - many to many relationship.


    Lets use Stackoverflow as an example starting with a one to many relationship and ending with a many to many relationship:

    Authors
    Joel
    Jeff
    
    Books
    Stackoverflow Joel
    

    Poor Jeff, he is not credited with stackoverflow from the above example...so we need to fix that:

    Author
    Joel
    Jeff
    
    Books
    Stackoverflow
    
    AuthorBooks
    Stackoverflow Jeff
    Stackoverflow Joel
    

    Now everyone's happy...

提交回复
热议问题