2012-05-29 94 views
1

我堅持這個錯誤在mysql中沒有150的問題,我知道已經有問題 其中討論這個問題,但我仍然無法找到我在哪裏錯了。這裏是我試圖創建數據庫:MySQL錯誤150:無法創建表

create table business (
    ident varchar(40) NOT NULL, 
    name varchar(50) NOT NULL, 
    rating INT UNSIGNED NOT NULL, 
    PRIMARY KEY(ident) 
) ENGINE=InnoDB; 

create table deals (
    business_id varchar(40) NOT NULL, 
    deals_id varchar(20) NOT NULL, 
    deals_title varchar(50) NOT NULL, 
    PRIMARY KEY (business_id, deals_id), 
    FOREIGN KEY (business_id) REFERENCES business(ident) ON DELETE CASCADE 
) ENGINE=InnoDB; 

create table d_options (
    business_id varchar(40) NOT NULL, 
    dealid varchar(20) NOT NULL, 
    option_title varchar(40) NOT NULL, 
    PRIMARY KEY(business_id, dealid, option_title), 
    FOREIGN KEY(business_id) REFERENCES business(ident) ON DELETE CASCADE, 
    FOREIGN KEY(dealid) REFERENCES deals(deals_id) 
) ENGINE=InnoDB; 

我得到的錯誤:ERROR 1005(HY000):無法創建表 'test.d_options'(錯誤:150)

我知道國外要滿足的關鍵約束根據mysql文檔,父表中應該有一個索引,但我認爲在主鍵上有默認索引 。

的InnoDB的狀況的結果是:

120530 0:47:48 Error in foreign key constraint of table test/d_options: 
FOREIGN KEY(dealid) REFERENCES deals(deals_id) 
) 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. 

任何幫助appriciated。

+0

該錯誤消息似乎很明顯 - 有沒有指標在FK目標列上... – DCoder

+0

但是由於目標鍵是其表中的主鍵之一,所以應該有一個索引。我應該爲該密鑰創建一個額外的索引,如果是的話,它不會成爲數據庫的額外負擔 –

回答

5

您對(business_id, deal_id)複合主鍵,它們被編入索引的一對,但要滿足FK,您需要deal_id單獨另一個指標:

create table deals (
    business_id varchar(40) NOT NULL, 
    deals_id varchar(20) NOT NULL, 
    deals_title varchar(50) NOT NULL, 
    PRIMARY KEY (business_id, deals_id), 
    FOREIGN KEY (business_id) REFERENCES business(ident) ON DELETE CASCADE, 
    /* Add an index on deals_id, separate from the compound PK */ 
    INDEX idx_deals_id (deals_id) 
) ENGINE=InnoDB; 
相關問題