我在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.
任何帮助都是适当的。
答案 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;