0

I have a ques similar to: How to create foreign key that is also a primary key in MySQL?

however my schema seems to match the answer but still returns the error "ERROR 1005 (HY000): Can't create table (errno: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;

Thanks in advance

Community
  • 1
  • 1

1 Answers1

0

To define a foreign key, the referenced field must have indexed.

As per documentation on foreign key constraints:

REFERENCES tbl_name (index_col_name,...)

Define an INDEX on item_id in table po_items and it should be working.

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;

Refer to:

[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]

reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION

Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
  • thanks so much Ravinder - I didn't get the 'reference the relation' in the earlier question, this has made it clearer for me – user3483825 Apr 01 '14 at 07:19