我想知道为什么我无法添加这个外键。这是我的架构
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
我的架构有问题吗?。
答案 0 :(得分: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
能够的。)
来自manual:
InnoDB允许外键引用任何索引列或列组。但是,在引用的表中,必须有一个索引,其中引用的列被列为相同顺序的第一列。