我有一个包含以下表格的数据库:Comments
,Articles
,Videos
,Songs
,Games
,Books
- Comments
与其他人之间的关系很多(文章,视频,歌曲......可能会有很多评论)。我有一个关联表CommentBelongsTo
有三列comment_id
,page_type
,page_id
),例如page_type = 'article'
和page_id = 1
,表示评论属于id = 1的文章。问题是如何根据page_id
将page_type
设置为外键?或者有更好的桌子设计吗?
答案 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';
获取特定类型的评论