MySQL FK错误1005 - 与FK相同的PK

时间:2014-04-01 06:26:35

标签: mysql sql foreign-keys primary-key

我有类似的问题: 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;

提前致谢

1 个答案:

答案 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 |没有行动