简体   繁体   中英

Failed to create table because of foreign key constraints

I'm trying to create three tables but I get error on the last one regarding its foreign key, I made sure that the foreign key has the same type in the two tables, same specifications, and it is a primary key in the parent table.
I tried also solutions that were suggested in previous posts but the situation wasn't the same so it didn't work.

CREATE TABLE Movies (
   movie_title VARCHAR(86), 
   imdb_id VARCHAR(9), 
   movie_id INT, 
   runtime INT, 
   budget INT, 
   revenue INT, 
   release_date DATE, 
   vote_count INT, 
   vote_average DOUBLE, 
   popularity DOUBLE, 
   language VARCHAR(2), 
   tagline VARCHAR(221), 
   overview TEXT(992), 
   PRIMARY KEY (movie_id), 
   FULLTEXT idx (overview)
);

I get: SUCCESFULLY CREATED TABLE Movies

CREATE TABLE Movie_Genre (
   movie_id INT,
   genre_id INT,
   PRIMARY KEY (movie_id, genre_id),
   FOREIGN KEY (movie_id) REFERENCES Movies(movie_id)
);

I get: SUCCESFULLY CREATED TABLE Movie_Genre

CREATE TABLE Genres (
   genre_id INT,
   genre_name VARCHAR(15),
   PRIMARY KEY (genre_id),
   FOREIGN KEY (genre_id) REFERENCES Movie_Genre(genre_id)
);

I get:

Failed to add the foreign key constraint. Missing index for constraint 'Genres_ibfk_1' in the referenced table 'Movie_Genre'

Your structure does not make any sense to me. I assume you want to store which movie has which genres. Therefore your Genre table should not have any foreign keys.

You need both movie_id and genre_id to be a foreign key in your Movie_Genre table:

CREATE TABLE Movie_Genre (
   movie_id INT,
   genre_id INT,
   PRIMARY KEY (movie_id, genre_id),
   FOREIGN KEY (movie_id) REFERENCES Movies(movie_id),
   FOREIGN KEY (genre_id) REFERENCES Genres(genre_id)
);

And drop your foreign key in your Genres table:

CREATE TABLE Genres (
   genre_id INT,
   genre_name VARCHAR(15),
   PRIMARY KEY (genre_id)
);

Note that you have to create Genres before Movie_Genres now.

The foreign key should be on the movie_genre table, not the genres table

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM