2016-12-29 26 views
0

我正在創建一個數據庫,必須管理食品運輸公司(學校項目)的訂單。我創建了一個菜單表,當然必須包含幾個菜餚(起動器,主菜和沙漠),我也有一個餐桌。所以菜單必須包含三個參考盤子表主鍵的foreign keys。但是,我得到一個錯誤,由於外鍵約束,每次我試圖執行我的腳本 這裏是對錶的代碼的時間(抱歉,但有一個問題,與插入代碼插入的情況下)問題與表中將引用幾個外鍵只會引用一個表

create table plat(
    id_plat integer primary key, 
    gluten boolean, 
    végétarien boolean, 
    nom varchar(30), 
    catégorie varchar(30) 
); 

create table menu(
    id_menu integer primary, 
    entrée integer, 
    plat integer, 
    dessert integer, 
    foreign key(entrée) references plat(id_menu), 
    foreign key(plat) references plat(id_menu), 
    foreign key(dessert) references plat(id_menu) 
); 

我執行後使用show ENGINE INNODB STATUS我的代碼我得到這個錯誤:

2016-12-29 21:42:58 7f2116e5c700 Error in foreign key constraint of table PROJET/menu: there is no index in referenced table which would contain the columns as the first columns, or the data types in the referenced table do not match the ones in table.

Constraint: CONSTRAINT "menu_ibfk_1" FOREIGN KEY ("entrée") REFERENCES "plat" ("id_menu")

The index in the foreign key in table is "entrée" See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html for correct foreign key definition.

回答

0

你的外鍵的定義是不正確的,你嘗試entree場從menuid_menu字段從plat錶鏈接。試試這個方法:

foreign key(entrée) references plat(id_plat) 

Official docs

+0

是好的,如果我的外鍵具有相同的名稱作爲主鍵引用它? –

+0

@AkramBendoukha你是指Fk本身的名稱還是引用主鍵的字段? (如果是前者,我通常儘量避免明確地命名這些鍵;但它可能是正確的;如果是後者,通常情況下引用字段與引用的pk字段使用相同的名稱;是否良好實踐取決於例如,就你的情況而言,'menu'不能有3個引用'plat',沒有單獨的字段,每個字段都有自己的名字。) – Uueerdo

相關問題