【问题标题】:DataBase design: one to many database?数据库设计:一对多数据库?
【发布时间】:2013-06-05 01:37:38
【问题描述】:

我对数据库设计非常陌生。

我有一个疑问。这个问题非常基本。但请帮帮我。我会尝试通过一个例子来解释它。

假设,我把书放在一张桌子上,而他们的作者放在另一张桌子上(假设一本书只由一位作者(一对多)写,而一位作者可以写多本书(多对一))。 我不知道如何准确链接表格以及应该自动增加什么?

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?

    }   

帮助赞赏

【问题讨论】:

  • authorID 会自动递增,Field3 实际上会在 tblBooks 中并被称为 authorID 来链接它们
  • @PatrickEvans 所以在一对多关系中,链接字段位于第一个表中?这个字段是否称为外键?
  • 是的,“Many”表获取“One”表的外键。

标签: database database-design one-to-many


【解决方案1】:

“Many”表获取“One”表的外键。

tblBooks {
    bookId   
    bookName
    authorId
}
tblAuthors {
    authorId  
    authorName
}  

示例查询

//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

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

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

tblBooks {
    bookId
    bookName
}

tblAuthors {
    authorId
    authorName
}

tblBookAuthors {
    bookId
    authorId
}

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

tblBooks {
    bookId
    bookName
    authorIds
}

tblAuthor {
    authorId
    authorName
}

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

决定多对多结构中哪个表获取逗号分隔ID的字段的方法是不经常删除外国ID的表,例如作者通常不被删除或添加到一本书,因此它可以获取列表字段。

【讨论】:

【解决方案2】:

@Patrick evans 是正确的。链接字段在子表中。为您安排,

tblBooks     //Table 1 contains Books
{
 bookId     Primary Key // This field is auto-incremented
 bookName
 AuthorId   Foreign Key constraint references tblAuthors.AuthorId
}


tblAuthors    //Table 2
{
 authorId,  Primary Key // this field can also be auto-incremented
 authorName
}

【讨论】:

  • 好的,我明白了!那么,我是否可以得出结论,在一对多关系中,外键始终位于第一个表中(与一对多相关的表)?
  • 如果你的意思是子表,(在 1many 关系的许多方面),那么是的。
【解决方案3】:

Field3 可以放在tblBooks 中并调用,例如,定义为外键的authorId。您可以添加这样的约束

ALTER TABLE tblBooks
ADD CONSTRAINT fk_author
FOREIGN KEY (authorId)
REFERENCES tblAuthors(authorId)

在这种情况下bookId 不应该是唯一的,因为在表tblBooks 中会有多个输入具有相同的authorId

顺便说一句,外键是一个表中的一个字段(或字段集合),它唯一地标识另一个表的一行。

【讨论】:

  • 请您解释一下。首先,我应该将 bookId 和 authorId 都设置为自动递增吗?
  • 可以,但没必要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-29
相关资源
最近更新 更多