我有类似的问题: How to create foreign key that is also a primary key in MySQL?
但是我的架构似乎与答案匹配,但仍然返回错误“ERROR 1005(HY000):无法创建表(错误号:150)”
CREATE TABLE po_items (
job_id CHAR(3) NOT NULL,
po_id CHAR(3) NOT NULL,
item_id CHAR(3) NOT NULL,
quantity SMALLINT,
PRIMARY KEY (job_id, po_id, item_id),
FOREIGN KEY (job_id, po_id) REFERENCES pos(job_id, po_id)
) ENGINE = INNODB;
CREATE TABLE items (
item_id CHAR(3) NOT NULL,
descr CHAR(10),
on_hand SMALLINT,
price DECIMAL(5,2),
PRIMARY KEY (item_id),
FOREIGN KEY (item_id) REFERENCES po_items(item_id)
) ENGINE = INNODB;
提前致谢
答案 0 :(得分:0)
要定义foreign key
,引用的字段必须已编入索引。
根据foreign key
约束的文档:
REFERENCES tbl_name(index_col_name,...)
在表INDEX
中的item_id
上定义po_items
,它应该正常运行。
CREATE TABLE po_items (
job_id CHAR(3) NOT NULL,
po_id CHAR(3) NOT NULL,
item_id CHAR(3) NOT NULL,
quantity SMALLINT,
KEY (item_id),
PRIMARY KEY (job_id, po_id, item_id),
FOREIGN KEY (job_id, po_id) REFERENCES pos(job_id, po_id)
) ENGINE = INNODB;
请参阅:
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name](index_col_name,...)
参考文献tbl_name(index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]reference_option:
限制| CASCADE | SET NULL |没有行动