外键基于另一列

时间:2018-05-14 09:58:38

标签: mysql sql database foreign-keys one-to-many

我有一个包含以下表格的数据库:CommentsArticlesVideosSongsGamesBooks - Comments与其他人之间的关系很多(文章,视频,歌曲......可能会有很多评论)。我有一个关联表CommentBelongsTo有三列comment_idpage_typepage_id),例如page_type = 'article'page_id = 1,表示评论属于id = 1的文章。问题是如何根据page_idpage_type设置为外键?或者有更好的桌子设计吗?

1 个答案:

答案 0 :(得分:0)

以下表结构可以解决问题

DROP TABLE IF EXISTS `test`.`article`;
CREATE TABLE  `test`.`article` (
  `idArticle` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Name` varchar(45) NOT NULL DEFAULT '',
  PRIMARY KEY (`idArticle`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `test`.`games`;
CREATE TABLE  `test`.`games` (
  `idGames` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL DEFAULT '',
  PRIMARY KEY (`idGames`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `test`.`comments`;
CREATE TABLE  `test`.`comments` (
  `idComments` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `a_id` int(10) unsigned DEFAULT NULL,
  `g_id` int(10) unsigned DEFAULT NULL,
  `Comment` varchar(45) NOT NULL DEFAULT '',
  PRIMARY KEY (`idComments`),
  KEY `FK_Comments_1` (`a_id`),
  KEY `FK_Comments_2` (`g_id`),
  CONSTRAINT `FK_Comments_1` FOREIGN KEY (`a_id`) REFERENCES `article` (`idArticle`),
  CONSTRAINT `FK_Comments_2` FOREIGN KEY (`g_id`) REFERENCES `games` (`idGames`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

insert into article values (1,'A1');
insert into comments values (1,1,null,'A1 comment')
insert into games values (1,'G1');
insert into comments values (1,null,1,'G1 comment')

select * from comments where a_id<>'NULL';

获取特定类型的评论