2

我想知道为什么我不能添加这个外键。这是我的架构

CREATE TABLE members(
  member_id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  num_1 int,
  num_2 int,
  password VARCHAR(50) NOT NULL,
  PRIMARY KEY (member_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE contacts(
  contact_id INT NOT NULL AUTO_INCREMENT,
  s1 int,
  phone_number VARCHAR(10) NOT NULL,
  s2 int,
  s3 int,
  PRIMARY KEY (contact_id),
  FOREIGN KEY (s1) REFERENCES members(num_1) ON DELETE CASCADE ON UPDATE CASCADE,
  FOREIGN KEY (s2) REFERENCES members(num_2) ON DELETE CASCADE ON UPDATE CASCADE,
  FOREIGN KEY (s3) REFERENCES members(member_id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8

我在 mysql 终端上收到此错误 ERROR 1215 (HY000): Cannot add foreign key constraint

我的架构有问题吗?

4

1 回答 1

5

以这种方式为我工作:

CREATE TABLE members(
  member_id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  num_1 int,
  num_2 int,
  password VARCHAR(50) NOT NULL,
  PRIMARY KEY (member_id),
  key idx_num1 (num_1),
  key idx_num2 (num_2)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE contacts(
  contact_id INT NOT NULL AUTO_INCREMENT,
  s1 int,
  phone_number VARCHAR(10) NOT NULL,
  s2 int,
  s3 int,
  PRIMARY KEY (contact_id),
  FOREIGN KEY (s1) REFERENCES members(num_1) ON DELETE CASCADE ON UPDATE CASCADE,
  FOREIGN KEY (s2) REFERENCES members(num_2) ON DELETE CASCADE ON UPDATE CASCADE,
  FOREIGN KEY (s3) REFERENCES members(member_id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

刚刚添加

  key idx_num1 (num_1),
  key idx_num2 (num_2)

在表成员中。外键需要引用索引列(不一定唯一,也不一定NOT NULL能够)。

手册

InnoDB 允许外键引用任何索引列或列组。但是,在引用的表中,必须有一个索引,其中引用的列按相同顺序列为第一列。

于 2013-07-03T08:39:21.213 回答