Is order of execution important when creating Primary/Foreign Key links in a MySQL statement?
For example, the following code will produce the error: "Cannot add foreign key constraint"
CREATE TABLE IF NOT EXISTS Movies
(
MovieID INT NOT NULL AUTO_INCREMENT,
GenreID INT NOT NULL,
PRIMARY KEY(MovieID),
FOREIGN KEY(GenreID) References Genres(GenreID)
);
CREATE TABLE IF NOT EXISTS Genres
(
GenreID INT NOT NULL AUTO_INCREMENT,
GenreName VARCHAR(30),
Primary key (GenreID)
);
Cannot add foreign key constraint
But when the Genre table is created FIRST, the error no longer persists:
CREATE TABLE IF NOT EXISTS Genres
(
GenreID INT NOT NULL AUTO_INCREMENT,
GenreName VARCHAR(30),
Primary key (GenreID)
);
CREATE TABLE Movies
(
MovieID INT NOT NULL AUTO_INCREMENT,
GenreID INT NOT NULL,
PRIMARY KEY(MovieID),
FOREIGN KEY(GenreID) References Genres(GenreID)
);
Schema Ready
Is the error caused because the table hasn't been created yet, so it doesn't know where / what the Genre tables PK type is?
When I was searching for a solution to foreign key constraints all I found was information on the data type matching, but not the order of execution. Thanks.
Is the error caused because the table hasn't been created yet, so it doesn't know where / what the Genre tables PK type is?
Yes.
If you define the Movies
table first, MySQL is going to try to find the referenced Genres
table, which does not yet exist. So you should create them in the opposite order:
CREATE TABLE IF NOT EXISTS Genres
CREATE TABLE IF NOT EXISTS Movies
Foreign key is a reference to another key: primary key. If primary key doesn't exist now, you can not reference to an unknown thing, so you get exception.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.