暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

数据库多态关联外键解决方案

原创 aisql 2021-09-16
215

假定今日头条有视频,图片,文章贴 三个表
videos
(
videoid --视频id PRI

)
photos
(
photoid --图片id PRI

)
articles
(
artid --文章id PRI

)
终端用户可以在视频、图片、文章下面评论 请你建立评论的数据库表

你可能会这样建立

create table comments ( commid int comment '评论表ID', commText varchar(100) comment '评论内容 ', fromid int comment '被评内容id' fromtype int comment '1代表图片 2代表视频 3代表文章', primary key(commid) )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='评论表'

当fromtype = 1 时 需关联 comments.fromid = photos.photoid
当fromtype = 2 时 需关联 comments.fromid = videos.videoid
当fromtype = 2 时 需关联 comments.fromid = articles.artid

你会发现 没有办法为fromid 建立外键。 后端应用建立实体、业务逻辑也会较复杂

解决方案为: 增加三个中间表

create table comments ( commid int comment '评论表ID', commText varchar(100) comment '评论内容 ', primary key(commid) )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='评论表' create table videos_comments ( vcid int comment '视频评论表主键', commid int comment '评论表id', videoid int comment '视频表id', primary key(vcid), constraint fk_comments_commid foreign key(commid) references comments(commid), constraint fk_videos_videoid foreign key(videoid) references videos(videoid) )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='视频评论表' create table photos_comments ( pcid int comment '图片评论表id', commid int comment '评论表id', photoid int comment '图片表id', primary key(vcid), constraint fk_comments_commid foreign key(commid) references comments(commid), constraint fk_photos_photoid foreign key(photoid) references photos(photoid) )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='图片评论表' create table articles_comments ( acid int comment '文章评论表id', commid int comment '评论表id', photoid int comment '图片表id', primary key(vcid), constraint fk_comments_commid foreign key(commid) references comments(commid), constraint fk_articles_artid foreign key(artid) references articles(artid) )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='图片评论表'

有大佬如果问为什么不在 photos、videos、articles 表中加一个 commid 指向评论表的评论ID呢?
如果一张图片最多只能有一条评论,是可以采用这种依赖倒置思想的,但如果一张图片有多条评论呢?就显然 不能在photos表中加commid了。 就只能采用上述建表方法。

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论