我有问题
和答案
表格,每个表格都有一个主键id
。
以及一个具有以下结构的表votes
:
CREATE TABLE `answers` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
//whatever
PRIMARY KEY (`id`)
)
CREATE TABLE `questions` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
//whatever
PRIMARY KEY (`id`)
)
CREATE TABLE `votes` (
`item_model` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`item_id` int(10) NOT NULL,
`vote` int(1) NOT NULL,
KEY `item_id_model` (`item_model`,`item_id`)
)
The index on votes consists of 2 columns:
item_model: string - can have one of 2 values: 'Question' or 'Answer'
item_id: integer - references the question or answer's id
如何在votes
上添加外键约束以引用表questions
和answers
上的ID。有没有办法通过组合两个变量来构成唯一的引用(item_model
和 item_id
)?
或者我选择的投票结构是不好的做法,这意味着我应该创建两个数据透视表 answer_vote
和 question_vote
?
最佳答案
作为第一个问题的答案...
不,不可能将两列(item_model,item_id)
组合成引用两个可能表的外键约束,具体取决于item_model
的值。
您可以保留设计。就当前的实现而言,不可能声明这样的 FOREIGN KEY 约束。
<小时/>就替代设计而言,可以考虑的一种可能性是定义两个个单独的列,一个作为问题
的FK,另一个作为问题的FK >回答
id int COMMENT 'the vote id'
item_model ENUM('Question','Answer')
question_id int NULL COMMENT 'FK ref question.id'
answer_id int NULL COMMENT 'FK ref answer.id'
vote TINYINT
然后我们可以声明两个单独的外键约束。
如果您想强制执行一条规则,即当 item_model 为“问题”时,answer_id 应为 NULL,question_id 应填充(非 NULL),则可以在 BEFORE INSERT 和 BEFORE UPDATE 触发器中强制执行。
关于两列上的 MySQL 外键 : integer AND string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42661389/