【问题标题】:Foreign key based on another column基于另一列的外键
【发布时间】:2018-05-14 09:58:37
【问题描述】:
我有一个包含以下表格的数据库:Comments、Articles、Videos、Songs、Games、Books 在 Comments 和其他数据库之间具有一对多关系(一个文章、视频、歌曲……可能有很多cmets)。我有一个关联表CommentBelongsTo 有三列comment_id、page_type、page_id),例如如果page_type = 'article' 和page_id = 1,表示评论属于id = 1 的文章。问题是如何根据page_type 将page_id 设置为外键?或者有没有更好的餐桌设计?
【问题讨论】:
标签:
mysql
sql
database
foreign-keys
one-to-many
【解决方案1】:
如下表结构可以解决问题
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';
获取特定类型的 cmets