嘿,我是 SQL 的新手,我正在尝试创建一个博客,计划就像一个博客只能有一个作者,一个作者可以有多个博客,一个博客可以有多个图像
任何人都可以让我理解这种关系对于 sql 映射将如何变化?
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
有blogId
and ImageId
,这意味着一个imageID
可以有多个blogIds
,所以多个博客使用相同的图像满足您的要求
作者 ----> 博客 -------> 图片..
所以让我稍微解释一下这个计划。
将有一个表作者,其中包含作者的所有详细信息。PK 是 author_id。博客表将包含博客的详细信息。Blog_id 是 PK 并且将具有由作者表引用的外键 author_id。图像表将包含图像的详细信息。image_id 是 pk 并且将具有 blog 表引用的外键 blog_id。
该行为被称为一对多关系
设置一个带有 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
有了这个,您可以在 Author ID 或 Blog Id 上使用 SQL Join 来获取下一个表中的数据。