Keep getting foreign key constraint failed message in My SQL

10.7k Views Asked by At

I tried to insert data into the table Bookratings, but I keep getting this error message. Is this because when I try to insert, it creates duplicates in the Bookratings table, which is not allowed by the PRIMARY key constraint?

MySQL Error 1452 - Cannot add or update a child row: a foreign key constraint fails

enter image description here

My actual code:

drop database if exists amazon2;

create database if not exists amazon2;

use amazon2;

create table books(  
  ISBN varchar(13),
  Title varchar(255),
  Author varchar(255),
  Year int(10),
  Puplisher varchar(255),
  ImageURL varchar(255),
  Genre varchar(12),
  unitprice decimal(6,2),
  primary key (ISBN)
); 


  create table users(
    UserID int(11),
    Country varchar(250),
    Age int(11),
    primary key (UserID)
  );


  create table bookratings(
    UserID int(11) not null,
    ISBN varchar(13) not null,
    Rating int(11),
    primary key (UserID, ISBN),
    foreign key (ISBN) references books (ISBN) on delete cascade on update cascade,
    foreign key (UserID) references users (UserID) on delete cascade on update cascade
   );


   create table orders(
     OrderID int(11),
     UserID int(11) not null,
     Year int(10),
     totalpay decimal(6,2),
     primary key (OrderID),
     foreign key (UserID) references users (UserID)
   );


   create table trans(
     OrderID int(11) not null,
     ISBN varchar(13) not null,
     Quantity int(11),
     primary key (OrderID, ISBN),
     foreign key (OrderID) references orders (OrderID),
     foreign key (ISBN) references books (ISBN)
   );

I have to clarify something: Given by the task, I am not allowed to add any other attributes or delete the existing attributes.

1

There are 1 best solutions below

0
On

Foreign key constraint violation means the table you're trying to update contains references to some other table, and you're somehow breaking that reference.

If I've got a table Movies

+----------+---------------+
| Movie_ID |  Movie_Name   |
+----------+---------------+
|        1 | Jaws          |
|        2 | Star-Wars     |
|        3 | Jurassic Park |
+----------+---------------+

And a table User_Reviews

+---------+----------+-------+
| User_ID | Movie_ID | Score |
+---------+----------+-------+
|       1 |        1 | 2.5   |
|       2 |        1 | 5     |
|       3 |        2 | 4     |
|       4 |        2 | 3     |
|       5 |        2 | 4.5   |
|       6 |        3 | 5     |
+---------+----------+-------+

In the User_Reviews table, Movie_ID is a foreign key.

I can't have a review with Movie_ID = 10, because that movie doesn't exist in the Movies table. If I did try to do that, I'd get a foreign key constraint error.