2011-06-28 46 views
4

這是show engine innodb status;錯誤消息當我嘗試創建表:想不通有什麼不對的外鍵約束聲明

------------------------ 
LATEST FOREIGN KEY ERROR 
------------------------ 
110628 16:56:07 Error in foreign key constraint of table test/menu_items: 
foreign key(id_menu) 
       references menus(id) 
       on update cascade 
       on delete cascade, 
     foreign key(id_item) 
       references items(id) 
       on update cascade 
       on delete cascade, 
     primary key(id_menu, id_item) 
) engine=InnoDB: 
Cannot find an index in the referenced table where the 
referenced columns appear as the first columns, or column types 
in the table and the referenced table do not match for constraint. 
Note that the internal storage type of ENUM and SET changed in 
tables created with >= InnoDB-4.1.12, and such columns in old tables 
cannot be referenced by such columns in new tables. 
See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html 
for correct foreign key definition. 

這些都是相關的SQL語句:

create table if not exists menus (                       
    id    mediumint unsigned not null auto_increment, 
    id_restaurant mediumint unsigned not null, 
    name   varchar(50) not null, 
    description  varchar(255) default null, 
    foreign key(id_restaurant) 
     references restaurants(id) 
     on update cascade 
     on delete cascade, 
    primary key(id) 
) engine=InnoDB; 

create table if not exists items (
    id    mediumint unsigned not null auto_increment, 
    id_restaurant mediumint unsigned not null, 
    name   varchar(50), 
    description  text, 
    type   enum('appetizer','salad','soup','entree','dessert','drink','other'), 
    price   decimal(4,2), 
    foreign key(id_restaurant) 
     references restaurants(id) 
     on update cascade 
     on delete cascade, 
    primary key(id) 
) engine=InnoDB; 

create table if not exists order_items (
    id_order  bigint unsigned not null, 
    id_item   mediumint unsigned not null, 
    item_name  varchar(50), 
    item_description text, 
    item_price  decimal(4,2), 
    notes   varchar(1024), 
    quantity  smallint unsigned, 
    foreign key(id_order) 
     references orders(id) 
     on update cascade 
     on delete cascade, 
    foreign key(id_item) 
     references items(id) 
     on update cascade 
     on delete cascade, 
    primary key(id_order, id_item) 
) engine=InnoDB; 

刪除menu_items.id_menu和相應的外鍵/主鍵可以正確分析SQL語句。

爲什麼我無法從menu_items創建菜單(id)的外鍵引用?

回答

15

你有數據類型不匹配:

create table order_items (
    id_order bigint unsigned not null, -- BIGINT 

create table items (
    id mediumint unsigned not null auto_increment, -- MEDIUMINT 

order_items.id_order引用items.id,所以他們應該是相同的。

嘗試改變ORDER_ITEMS id_order中等INT:

order_items (
    id_order  mediumint unsigned not null, 
+0

謝謝,我抓住了,只是現在還有。它一定是遲到了,因爲我在發佈前一直在注視這個問題30分鐘。 – wting