1

我被这个错误困住了,在 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): Can't create table 'test.d_options' (errno: 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.

任何帮助都会得到帮助。

4

1 回答 1

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;
于 2012-05-29T19:26:56.590 回答