DataBase设计:一对多数据库?

Nav*_*ini 0 database database-design one-to-many

我是数据库设计的新手.

我有个疑问.这个问题非常基础.但请帮帮我.我将尝试通过一个例子来证明它.

假设,我在一张桌子上拿到了书,在另一张桌子里拿到了他们的作者(假设一本书只由一位作者(一对多)写成,一位作者可以写多本书(多对一)).我没有得到如何准确链接表和什么应该自动递增?

tblBooks     //Table 1 contains two entities
    {
     bookId      // This field is auto-incremented
     bookName
    }


tblAuthors    //Table 2
    {
     authorId    // Should this field also be auto-incremented?
     authorName
     Field3      // What should be the 'Field3' then which acts as link between both the tables?
                 // What exactly is foreign key? Here 'Field3' would be foreign key or what?

    }   
Run Code Online (Sandbox Code Playgroud)

帮助赞赏

Pat*_*ans 6

"Many"表获取"One"表的外键.

tblBooks {
    bookId   
    bookName
    authorId
}
tblAuthors {
    authorId  
    authorName
}  
Run Code Online (Sandbox Code Playgroud)

示例查询

//Grabs EVERY book that was made by an author with id 1
SELECT * FROM tblBooks where authorId='1' 

//Grabs the author of the book with id 223
SELECT * FROM tblAuthors where authorId=(SELECT authorId FROM tblBooks WHERE bookId='223')

//Joins the tables so each book will show its author
SELECT 
    tblBooks.bookId,
    tblBooks.bookName,
    tblAuthors.authorName
    tblAuthors.authorId 
FROM 
    tblBooks 
JOIN 
    tblAuthors 
ON 
    tblBooks.authorId=tblAuthors.authorId
Run Code Online (Sandbox Code Playgroud)

语法可能会根据您使用的数据库(mysql,oracle,sqlite等)而改变,但这就是基本结构.

如果你决定使用多对多结构,你可以做几件事,一个创建第三个表,用于链接两个表,例如有很多作者的书:

tblBooks {
    bookId
    bookName
}

tblAuthors {
    authorId
    authorName
}

tblBookAuthors {
    bookId
    authorId
}
Run Code Online (Sandbox Code Playgroud)

或者在其中一个表中有一个字段,该字段具有逗号分隔的作者ID字符串:

tblBooks {
    bookId
    bookName
    authorIds
}

tblAuthor {
    authorId
    authorName
}
Run Code Online (Sandbox Code Playgroud)

authorIds就像1,12,32,在这种情况下,您将不得不使用数据库函数来选择该集合中的作者,例如MYSQL find_in_set(tblAuthors.authorId,tblBooks.authorIds)的第一个参数是搜索,第二个是您要搜索的数据集

决定多对多结构中哪个表使用逗号分隔的id获取字段的方法是不经常删除外来ID的表,例如作者通常不会被删除或添加到书中,所以它获取列表字段.