I have a set of sql statements,
CREATE TABLE PRICING(
CodeVillage INT,
TypeCabin INT,
CodeSeason CHAR(2),
WeekPrice INT,
PRIMARY KEY(CodeVillage, TypeCabin, CodeSeason)
);
CREATE TABLE SEASON(
CodeSeason CHAR(2) PRIMARY KEY,
NameSeason VARCHAR(20),
CONSTRAINT Fk_Pricing_CodeSeason Foreign KEY (CodeSeason)
REFERENCES PRICING(CodeSeason)
);
The sql gave me tips that
ERROR 1005 (HY000): Can't create table 'france.season' (errno: 150)
I know that the problem is on the foreign key but I don’t know why, could you help me figure out? This is just the creating matters, and the table pricing has no data in it.
4
Answers
I add an index after the definition part of the
Pricing
and it works!This is from the message in the
LATEST FOREIGN KEY ERROR
part, thanks for answers by Georg Richter who gave me inspirations. So I think the problem is that theCodeSeason
is on the 3rd part of the Primary Key, and the sql engine requires a first position based index or primary key or so.Since the error isn’t really verbose, execute
instead, which let you know some more details under section
LATEST FOREIGN KEY ERROR
:A foreign key establishes a 1:n relation. The parent table has a primary key, so each row is uniquely identifyable. The child table has a foreign key referencing this primary key, so as to say which parent row a child row belongs to.
You have mistakenly tried to place the foreign key in the parent table.
Actually the error message you got already implied that you need to create an index for the referenced column: 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. You don’t have to change your code, just create an index for the referenced column in the parent table before attempting to create the child table: