博客和作者之间的SQL关系

时间:2013-07-31 05:32:48

标签: mysql sql sqlite

heya我是SQL新手 我正在尝试创建一个博客 计划就像 一个博客只能有一个AUTHOR 作者可以拥有多个博客 一个博客可以有多个图像

任何人都可以让我理解sql映射的关系如何?

3 个答案:

答案 0 :(得分:1)

  

作者---->博客------->图像..

让我稍微解释一下这个计划。

将有一位表作者拥有作者的所有细节。 PK是author_id。 博客表将包含博客的详细信息。 Blog_id是PK,并且将具有作者表引用的外键author_id。 图像表将包含图像的详细信息。 image_id是pk,将有博客表引用的外键blog_id。

此行为称为one to many relation

答案 1 :(得分:1)

Create table Author
(
Id int
, Name nvarchar(max)
);

Create table Image
(
Id int
,ImagePath nvarchar(max)
);

Create table Blog
(
Id int
,Name nvarchar(max)
,AuthorId int
);

Create table BlogImages
(
Id int
,BlogId int
,ImageId int
);

ALTER TABLE Blog
ADD FOREIGN KEY (AuthorId)
REFERENCES Author(Id);

ALTER TABLE BlogImages
ADD FOREIGN KEY (BlogId)
REFERENCES Blog(Id);

ALTER TABLE BlogImages
ADD FOREIGN KEY (ImageId)
REFERENCES Image(Id);

在上述关系中,我们有BlogImages blogIdImageId表,这意味着单个imageID可以有多个blogIds,因此多个博客使用满足您要求的相同图像

答案 2 :(得分:0)

使用ID设置作者表。在您的博客表中,使用博客的唯一ID,并将作者ID作为列包含在内。最后,在您的图像表中,包括博客ID,也许还包括作者ID。你应该得到这样的东西:

Author id -------------> Blog Id -------------->Image ID
Other Author details     AuthorID               Blog Id
                         Other Blog details     Author ID
                                                Other Image data

使用此功能,您可以使用SQL Join on Author ID或Blog Id来获取下表中的数据。