I am building create scripts for my database, and am getting an error I cannot figure out. I have traced it down to a foreign key reference, but a Google search of the errno(150) has not been particularly helpful.
The script that fails:
create table ITEM_TBL(
IT_ITEM_ID_FLD INT AUTO_INCREMENT,
IT_ITEM_NAME_FLD VARCHAR(50),
ITY_ITEM_TYPE_FLD INT,
UT_USER_ID_FLD INT,
IT_CHECKOUT_STATUS_FLD VARCHAR(1),
IT_LAST_UPDATE_FLD DATE,
IT_LAST_ITEM_CHANGE_FLD DATE,
IT_ACTIVE_FLD VARCHAR(1),
PRIMARY KEY (IT_ITEM_ID_FLD),
FOREIGN KEY (UT_USER_ID_FLD)
REFERENCES USER_TBL(UT_USER_ID_FLD),
FOREIGN KEY (ITY_ITEM_TYPE_FLD)
REFERENCES ITEM_TYPE_TBL(ITY_ITEM_TYPE_FLD)
) ENGINE = INNODB;
(NOTE: it is the last foreign key that is causing the error, because when it is removed it works perfectly)
The foreign key referenced tables:
create table ITEM_TYPE_TBL(
ITY_ITEM_TYPE_ID_FLD INT AUTO_INCREMENT,
ITY_ITEM_TYPE_NAME_FLD VARCHAR(50),
PRIMARY KEY (ITY_ITEM_TYPE_ID_FLD)
) ENGINE = INNODB;
create table USER_TBL(
UT_USER_ID_FLD INT AUTO_INCREMENT,
UT_NAME_FLD VARCHAR(50),
UT_EMAIL_ADDRESS_FLD VARCHAR(50),
UT_CARD_NUMBER INT NOT NULL,
PRIMARY KEY (UT_USER_ID_FLD)
) ENGINE = INNODB;
The specific error I get is:
#1005 - Can't create table 'db.ITEM_TBL' (errno: 150)
Make sure that your tables (with indexes) already exist before creating the foreign key relationship. Like this
create table USER_TBL(
UT_USER_ID_FLD INT AUTO_INCREMENT,
UT_NAME_FLD VARCHAR(50),
UT_EMAIL_ADDRESS_FLD VARCHAR(50),
UT_CARD_NUMBER INT NOT NULL,
PRIMARY KEY (UT_USER_ID_FLD)
)ENGINE = INNODB;
create table ITEM_TYPE_TBL(
ITY_ITEM_TYPE_ID_FLD INT AUTO_INCREMENT,
ITY_ITEM_TYPE_NAME_FLD VARCHAR(50),
PRIMARY KEY (ITY_ITEM_TYPE_ID_FLD)
) ENGINE = INNODB;
create table ITEM_TBL(
IT_ITEM_ID_FLD INT AUTO_INCREMENT,
IT_ITEM_NAME_FLD VARCHAR(50),
ITY_ITEM_TYPE_FLD INT,
UT_USER_ID_FLD INT,
IT_CHECKOUT_STATUS_FLD CHAR(1),
IT_LAST_UPDATE_FLD datetime,
IT_LAST_ITEM_CHANGE_FLD DATE,
IT_ACTIVE_FLD CHAR(1),
primary key (IT_ITEM_ID_FLD),
FOREIGN KEY (UT_USER_ID_FLD)
REFERENCES USER_TBL(UT_USER_ID_FLD) ,
FOREIGN KEY (ITY_ITEM_TYPE_FLD)
REFERENCES ITEM_TYPE_TBL(ITY_ITEM_TYPE_ID_FLD)
) ENGINE = INNODB;
BTW, you also had a typo (ITY_ITEM_TYPE_ID_FLD vs ITY_ITEM_TYPE_FLD)
This works in sqlfiddle