2013-07-03 66 views
2

我很奇怪,爲什麼我不能添加該外國keys.This可以是我的架構多個外鍵不能被添加

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

有沒有我的模式有問題嗎?

+1

你可能沒有'num_1'和'num_2'上的索引。可能是原因 –

+0

通常外鍵需要引用表中的主鍵 –

+0

@JanneMatikainen我認爲唯一鍵 – chetan

回答

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的允許外鍵引用列的任何索引列或組。但是,在被引用的表中,必須有一個索引,其中被引用的列按照相同順序列爲第一列。