如果您想知道单个列是否可以有多个外键,那么答案是否定的。
如果你愿意,你可以有单独的外键。所以你可以像这样修改你的评论表 -
comment:
* comment_id (PK)
* PostID (FK to Post.PostID)
* PhotoID (FK to <Photo>.PhotoID)
* ProfileID (FK to <Profile>.ProfileID)
* Body
而且,您必须确保在 Comment 表中的 PostID、PhotoID 和 ProfileID 列中允许为空,并且还可能将默认值设置为空。
这是实现这一点的 DDL -
Create table Photo
(
PhotoID int,
PhotoDesc varchar(10),
Primary key (PhotoID)
)
Create table Post
(
PostID int,
PostDesc varchar(10),
Primary key (PostID)
)
Create table Profiles
(
ProfileId int,
ProfileDesc varchar(10),
Primary key (ProfileId)
)
Create table Comment
(
CommentID int,
PhotoID int,
PostID int,
ProfileId int,
body varchar(10),
Primary key (CommentID),
Foreign key (PhotoID) references Photo(PhotoID),
Foreign key (PostID) references Post(PostID),
Foreign key (ProfileId) references Profiles(ProfileId)
)
insert into Photo values (1,'Photo1')
insert into Photo values (2,'Photo2')
insert into Photo values (3,'Photo3')
insert into Post values (11,'Post1')
insert into Post values (12,'Post2')
insert into Post values (13,'Post3')
insert into Profiles values (111,'Profiles1')
insert into Profiles values (112,'Profiles2')
insert into Profiles values (113,'Profiles3')
insert into Comment (CommentID,PhotoID,body) values (21,1,'comment1')
insert into Comment (CommentID,PhotoID,body) values (22,3,'comment2')
insert into Comment (CommentID,PostID,body) values (23,11,'comment3')
insert into Comment (CommentID,PostID,body) values (24,12,'comment4')
insert into Comment (CommentID,ProfileId,body) values (25,112,'comment5')
insert into Comment (CommentID,ProfileId,body) values (26,113,'comment6')
-- to select comments seperately for Photos, profiles and posts
select * from Comment where PhotoID is not null
select * from Comment where ProfileId is not null
select * from Comment where PostID is not null