MySQL 两列上的外键:整数和字符串

MySQL foreign key on two columns: integer AND string

我有 table 用于 questionsanswers,每个都有一个主键 id

和具有以下结构的 table 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 上添加外键约束以引用 tables questionsanswers 上的 ID。有什么方法可以通过组合两个变量来构成唯一参考(item_modelitem_id)?

或者我选择的投票结构是不好的做法,这意味着我应该创建两个枢轴 tables answer_votequestion_vote

作为第一个问题的答案...

不,不可能将两列 (item_model,item_id) 组合成引用两个可能表的外键约束,具体取决于 item_model.

的值

你可以保留设计。就目前的实现而言,不可能像这样声明一个 FOREIGN KEY 约束。


至于替代设计,要考虑的一种可能性是定义 两个 单独的列,一个作为 FK 到 question,另一个作为 FK 到answer

  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

然后我们可以声明两个单独的外键约束。

如果您想强制执行 answer_id 应为 NULL 且 question_id 应在 item_model 为 'Question' 时填充(非 NULL)的规则,可以在 BEFORE INSERT 和 BEFORE UPDATE 触发器中强制执行。