2014-07-18 40 views
0

我想嘗試一些顯然很簡單,但我只是繼續有同樣的錯誤「無法添加外鍵約束」,任何人都可以幫助我嗎?我用的工作臺與SQL無法添加外鍵約束簡單的代碼幫助請

drop table if exists table2; 
create table if not exists table2(
    id_kind int not null, 
    id_bod int not null, 
    id_doc int not null, 

    primary key (id_kind, id_bod, id_doc) 
)engine=InnoDB default charset=latin1; 

drop table if exists table1; 
create table if not exists table1(
    id_mov int not null,  
    id_kind int not null, 
    id_prod int, 
    id_bod int not null, 
    id_doc int not null, 

    primary key (id_mov), 
    key id_kind (id_kind), 
    key id_bod (id_bod), 
    key id_doc (id_doc), 

    foreign key table1 (id_kind) references table2 (id_kind), 
    foreign key table1 (id_bod) references table2 (id_bod), 
    foreign key table1 (id_doc) references table2 (id_doc) 
)engine=InnoDB default charset=latin1; 
+0

id_kind需要爲表1的主鍵,這是不是讓你無法創建FK約束 –

+0

應該是'外鍵(id_kind)參考表1(id_mov)' –

+0

@RichardHansell這是通常的做法,但我很確定外鍵可以引用任何相同類型的列。 – Arth

回答

0

我敢肯定你正試圖將foreign keyconstraint添加到錯誤的表。 推測table2包含由table1引用的種類。

你將不得不重新安排你的代碼,id_kind也許應該是primary keytable2,你需要在table1id_kind指數:

drop table if exists table2; 
create table if not exists tabla2(
    id_kind int not null, 
    primary key (id_kind) 
)engine=InnoDB default charset=latin1; 

drop table if exists table1; 
create table if not exists table1(
    id_mov int not null, 
    id_kind int not null, 
    id_prod int, 
    primary key (id_mov), 
    key id_kind (id_kind), 
    foreign key table1_ibfk_1 (id_kind) references table2 (id_kind) 
)engine=InnoDB default charset=latin1; 

UPDATE

現在看起來像你想要一個複合外鍵,試試這個爲你的表1:

drop table if exists table1; 
create table if not exists table1(
    id_mov int not null,  
    id_kind int not null, 
    id_prod int, 
    id_bod int not null, 
    id_doc int not null, 

    primary key (id_mov), 
    key id_kind_id_bod_id_doc (id_kind, id_bod, id_doc), 
    foreign key table1_ibfk_1 (id_kind, id_boc, id_doc) 
     references table2 (id_kind, id_boc, id_doc), 
)engine=InnoDB default charset=latin1; 

我還不確定每個表格代表什麼,或者你想要達到什麼目的。

您使用KEY(代名詞INDEX)行設立INDEX在表的FOREIGN KEY用途。

FOREIGN KEY docs

+0

是的,謝謝,這似乎工作,但我有一些疑問 – user3360931

+0

沒問題,你有什麼疑問? – Arth

+0

*爲什麼你必須添加'key id_kind(id_kind)'?那是做什麼的? *當我嘗試放入多個外鍵時,出現同樣的錯誤:S我將更新我的問題 – user3360931