MySQL Error: 1452 - Cannot add or update a child row - mysql

Error seems to occur when I try to INSERT into Items_Puchased (bottom lines). Ignore all comments.
Error Code: 1452. Cannot add or update a child row: a foreign key
constraint fails (shippingcontainers.items_purchased, CONSTRAINT
items_purchased_ibfk_2 FOREIGN KEY (container) REFERENCES stock
(container))
CREATE TABLE Customer (
customer_reference int UNIQUE AUTO_INCREMENT,
primary key (customer_reference),
forename VARCHAR(20),
surname VARCHAR(20),
contact VARCHAR(15),
email VARCHAR(50),
building VARCHAR(5),
road VARCHAR(40),
city VARCHAR(30),
postcode VARCHAR(7),
county VARCHAR(30));
CREATE TABLE Invoice (
invoice_reference int UNIQUE AUTO_INCREMENT,
customer_reference int UNIQUE,
primary key (invoice_reference),
foreign key (customer_reference) references Customer(customer_reference),
invoice_cost DECIMAL(20,2),
paid bit,
order_date DATETIME,
delivery_date DATE);
CREATE TABLE Stock (
container VARCHAR(10) UNIQUE NOT NULL DEFAULT 0,
primary key (container),
SBADNLon INT(4),
SBADNFel INT(4),
SBADNSou INT(4),
CHECK (container = ("SBADN-Lon" > 0, "SBADN-Fel" > 0, "SBADN-Sou" > 0)));
This is just showing 3 of the possible container variations
Each attribute stores a value containing the number of that model available in inventory
CREATE TABLE Items_Purchased (
container_ordered int UNIQUE AUTO_INCREMENT,
invoice_reference int,
container VARCHAR(10) NOT NULL DEFAULT "None",
container_cost decimal(20,2) NULL,
container_size VARCHAR(6) NOT NULL,
colour VARCHAR(5) NOT NULL,
grade CHAR(1) NOT NULL,
depot VARCHAR(15) NOT NULL,
container_type VARCHAR(20) NOT NULL,
conditionn VARCHAR(4) NOT NULL,
primary key (container_ordered, container_size, colour, grade, depot, container_type, conditionn));
foreign key (invoice_reference) references Invoice (invoice_reference),
foreign key (container) references Stock (container),
foreign key (container_size) references Container_Size (container_size),
foreign key (colour) references Colour (colour),
foreign key (grade) references Grade (grade),
foreign key (depot) references Depot (depot),
foreign key (container_type) references Container_Type (container_type),
foreign key (conditionn) references Conditionn (conditionn));
CREATE TABLE Depot (
depot VARCHAR(15) NOT NULL,
container_ordered int,
primary key (depot),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (depot = ("london","felixstowe","southampton")));
CREATE TABLE Container_Type (
container_type VARCHAR(20) NOT NULL,
container_ordered int,
primary key (container_type),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (container_type = ("dry","inslated","refreigerated","open top","tunnel")));
CREATE TABLE Container_Size (
container_size VARCHAR(6) NOT NULL,
container_ordered int,
primary key (container_size),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (container_size = ("small","medium","large")));
CREATE TABLE Colour (
colour VARCHAR(5) NOT NULL,
container_ordered int,
primary key (colour),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (colour = ("black","green")));
CREATE TABLE Conditionn (
conditionn VARCHAR(4) NOT NULL,
container_ordered int,
primary key (conditionn),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (conditionn = ("new","used")));
CREATE TABLE Grade (
grade CHAR(1) NOT NULL,
container_ordered int,
primary key (grade),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (grade = ("a","b","c")));
I am unsure on why I am getting this error code, can anyone assist? It occurs when adding
INSERT INTO Customer (
forename, surname, contact, email, building, road, city, postcode, county)
VALUES (
"james", "kelly", 07930317616, "james#uni.com", 123, "Yellow Road", "Ipswich", "IP11SQ", "Suffolk");
INSERT INTO Customer (
forename, surname, contact, email, building, road, city, postcode, county)
VALUES (
"ben", "smith", 0793031754, "ben#uni.com", 45, "Red Road", "Woodbridge", "IP142DD", "Suffolk");
INSERT INTO Invoice (
invoice_cost, paid, order_date, delivery_date)
VALUES (
1435.34, 1, 19/12/2017, 21/12/2017);
INSERT INTO Invoice (
invoice_cost, paid, order_date, delivery_date)
VALUES (
1035.12, 0, 02/02/2018, 29/12/2017);
INSERT INTO Stock (
SBADNLon, SBADNFel, SBADNSou)
VALUES (
3, 2, 1);
INSERT INTO Items_Purchased (
container_cost, container_size, colour, grade, depot, container_type, conditionn)
VALUES (
1645.21, "large", "black", "a", "london", "insulated", "new")

Look at your foreign key relationships with the Items_Purchased table. It sounds like you have a mismatch happening. And in looking at your table definition, you have a lot of foreign keys identified. This type of spider web construction is not typical and can cause you many problems. I would also take another look at your foreign keys and assess what the need is for each of them.

Your default value in table stock for column container is 0 and the default value for that column in the Items_Purchased table is "None".
As you don't assign any value for those columns in your insert statements, when you try to insert into the Items_Purchased table, it uses the default value for the column container "None" and this value doesn't exist in your stock table (the only value that exists it's 0).
You should make them the same value, or as default, in your Items_Purchased table set it as 0 like:
CREATE TABLE Items_Purchased (
container_ordered int UNIQUE AUTO_INCREMENT,
invoice_reference int,
container VARCHAR(10) NOT NULL DEFAULT 0,
container_cost decimal(20,2) NULL,
container_size VARCHAR(6) NOT NULL,
colour VARCHAR(5) NOT NULL,
grade CHAR(1) NOT NULL,
depot VARCHAR(15) NOT NULL,
container_type VARCHAR(20) NOT NULL,
conditionn VARCHAR(4) NOT NULL,
primary key (container_ordered, container_size, colour, grade, depot, container_type, conditionn));
foreign key (invoice_reference) references Invoice (invoice_reference),
foreign key (container) references Stock (container),
foreign key (container_size) references Container_Size (container_size),
foreign key (colour) references Colour (colour),
foreign key (grade) references Grade (grade),
foreign key (depot) references Depot (depot),
foreign key (container_type) references Container_Type (container_type),
foreign key (conditionn) references Conditionn (conditionn));

Related

MySQL #1215 Issue

I keep getting an issue with creating this table in my database. The issue is:
Error:1215 Cannot add foreign key constraint.
This is the table I am trying to make:
CREATE TABLE Customer (
customer_reference int UNIQUE AUTO_INCREMENT,
primary key (customer_reference),
forename VARCHAR(20),
surname VARCHAR(20),
contact VARCHAR(15),
email VARCHAR(50),
building VARCHAR(5),
road VARCHAR(40),
city VARCHAR(30),
postcode VARCHAR(7),
county VARCHAR(30));
CREATE TABLE Invoice (
invoice_reference int UNIQUE AUTO_INCREMENT,
customer_reference int UNIQUE,
primary key (invoice_reference),
foreign key (customer_reference) references Customer(customer_reference),
invoice_cost DECIMAL(20,2),
paid bit,
order_date DATETIME,
delivery_date DATE);
CREATE TABLE Stock (
container VARCHAR(10) UNIQUE NOT NULL DEFAULT 0,
primary key (container),
SBADNLon INT(4),
SBADNFel INT(4),
SBADNSou INT(4),
CHECK (container = ("SBADN-Lon" > 0, "SBADN-Fel" > 0, "SBADN-Sou" > 0)));
/* This is just showing 3 of the possible container variations
Each attribute stores a value containing the number of that model available in inventory
*/
CREATE TABLE Items_Purchased (
container_ordered VARCHAR(10) NOT NULL,
invoice_reference int,
container VARCHAR(10) NOT NULL DEFAULT "None",
container_cost decimal(20,2) NULL,
container_size VARCHAR(6) NOT NULL,
colour VARCHAR(5) NOT NULL,
grade CHAR(1) NOT NULL,
depot VARCHAR(15) NOT NULL,
container_type VARCHAR(20) NOT NULL,
conditionn VARCHAR(4) NOT NULL,
primary key (container_ordered, container_size, colour, grade, depot, container_type, conditionn),
foreign key (invoice_reference) references Invoice (invoice_reference),
foreign key (container) references Stock (container),
foreign key (container_size) references Container_Size (container_size),
foreign key (colour) references Colour (colour),
foreign key (grade) references Grade (grade),
foreign key (depot) references Depot (depot),
foreign key (container_type) references Container_Type (container_type),
foreign key (conditionn) references Conditionn (conditionn));
CREATE TABLE Depot (
depot VARCHAR(15) NOT NULL,
container_ordered VARCHAR(10) NOT NULL,
primary key (depot),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (depot = ("london","felixstowe","southampton")));
CREATE TABLE Container_Type (
container_type VARCHAR(20) NOT NULL,
container_ordered VARCHAR(10) NOT NULL,
primary key (container_type),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (container_type = ("dry","inslated","refreigerated","open top","tunnel")));
CREATE TABLE Container_Size (
container_size VARCHAR(6) NOT NULL,
container_ordered VARCHAR(10) NOT NULL,
primary key (container_size),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (container_size = ("small","medium","large")));
CREATE TABLE Colour (
colour VARCHAR(5) NOT NULL,
container_ordered VARCHAR(10) NOT NULL,
primary key (colour),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (colour = ("black","green")));
CREATE TABLE Conditionn (
conditionn VARCHAR(4) NOT NULL,
container_ordered VARCHAR(10) NOT NULL,
primary key (conditionn),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (conditionn = ("new","used")));
CREATE TABLE Grade (
grade CHAR(1) NOT NULL,
container_ordered VARCHAR(10) NOT NULL,
primary key (grade),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (grade = ("a","b","c")));
Thanks in advance
First of all, I believe it would be better to use another primary key for your table.
The datatypes of all the foreign key constraints should be exactly the same as how the fields are defined as primary keys in the original table. If container is varchar(20) in Stock table, for example, it has to be varchar(20) in Items_Purchased table.
Also, the collations defined (if any) would be the same, like utf-8 for those columns. Note that your tables might be in the same collaction, but the columns might have different, check properly.
Lastly, make sure the values for the foreign key values are unique and the definition of foreign key columns include not null
Reference: MySQL Error 1215: Cannot add foreign key constraint
the following 2 rules might have caused the error:
invoice_reference int UNIQUE auto_increment
foreign key (invoice_reference) references Invoice (invoice_reference)
The auto_increment property should be specified in the Invoice table (invoice_reference) instead.
I tried inserting each foreign key definition separately using the ALTER table command and it took it well - maybe some form of referencing issue?
My guess is, See in order to create a foreign key reference, the referenced table must be created before its reference is created. For example, check your third table. It contains a customer reference and it is working fine.
Now if you see DEPOT table and Items_Purchased table, both contains foreign key references on each other. Now think about it, In order to reference from Depot to Items_Purchased, Items_purchased must be present before Depot, and the vice versa must be true as well for referencing Items_Purchased to Depot. This will never be possible.
Please reconstruct your schema accordingly, and sort out which table should be created first, in order to get reference from that table.
This is more like a forward referencing error you face while compiling code in Java.

Cannot add foreign key here?

So I'm trying to create tables and I can't for the life of me understand why i keep getting and error saying "Cannot add foreign key to constraint".
The types are the same, the parent is a primary key, and they're NULLness is the same.
The problem is in the line in the create table for CDSingers where it says:
foreign key (track_num) references CDTracks (track_num),
(it's near the end)
It's the only table that won't be created and it's because of this line.
Please help.
(some of the other tables have been ommitted since they aren't connected)
create table CD
(
num int NOT NULL,
producer varchar(100) NOT NULL,
cd_number varchar(100) NOT NULL,
title varchar(100) NOT NULL,
type varchar(100) ,
band_name varchar(100) ,
production_date DATE NOT NULL,
price double CHECK (price >= 0),
foreign key (type) references MusicType (type),
foreign key (band_name) references Band (band_name),
primary key (num),
unique (producer, cd_number)
);
create table CDTracks
(
num int NOT NULL,
track_num int NOT NULL,
song_name varchar(100) NOT NULL,
minute int NOT NULL,
foreign key (num) references CD (num),
primary key (num, track_num)
);
create table Singer
(
id int NOT NULL,
singer_firstname varchar(100) NOT NULL,
singer_lastname varchar(100) NOT NULL,
primary key (id)
);
create table CDSingers
(
num int NOT NULL,
track_num int NOT NULL,
singer_id int NOT NULL,
foreign key (num) references CDTracks (num),
foreign key (track_num) references CDTracks (track_num),
foreign key (singer_id) references Singer (id),
primary key (num, track_num, singer_id)
);
You declare composite foreign keys like this:
foreign key (num, track_num) references CDTracks (num, track_num),

Getting ERROR 1452: Cannot add or update a child row: a foreign key constraint fails when using 1 our 4 insert statements

I am trying to insert data into my DB and I keep getting the "ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails" on 1 insert command. I believe it has to do with the FKs I used when I created the table. But I am not sure how to fix it. Any suggestions would be awesome.
Original Create table commands:
REATE TABLE Donut
(DonutID int,
DonutName VARCHAR(25) not null,
Description VARCHAR(25) not null,
UnitPrice decimal(4,2) not null,
PRIMARY KEY (DonutID) ) ;
CREATE TABLE Customer
( CustomerID INT not null,
FirstName VARCHAR(20) not null,
LastName VARCHAR(20) not null,
StreetAddress VARCHAR(20) not null,
Apt VARCHAR(20),
City VARCHAR(20) not null,
State VARCHAR(2) not null,
ZipCode VARCHAR(5) not null,
HomePhone VARCHAR(10) not null,
MobilePhone VARCHAR(10) not null,
OtherPhone VARCHAR(10),
PRIMARY KEY(CustomerID) ) ;
CREATE TABLE Orders
( OrderID int not null,
CustomerID int,
OrderDate Date not null,
Notes VARCHAR(100),
PRIMARY KEY (OrderID),
FOREIGN KEY (CustomerID)
REFERENCES Customer (CustomerID) ) ;
CREATE TABLE OrderItem
( OrderID INT,
DonutID INT,
Qty SMALLINT not null,
PRIMARY KEY(OrderID, DonutID),
FOREIGN KEY (OrderID)
REFERENCES Orders (CustomerID),
FOREIGN KEY (DonutID)
REFERENCES Donut (DonutID) ) ;
Insert command that is failing:
INSERT INTO OrderItem
(OrderID,DonutID,Qty) VALUES
(991,1,12),
(992,2,500),
(993,3,6);
This error is probably happening because one or both of your inserted records refer to records in the Orders and/or Donut tables which do not exist.
Try running the following queries:
SELECT *
FROM Orders
WHERE CustomerID IN (991, 992);
and this one:
SELECT *
FROM Donut
WHERE DonutID IN (1, 2);
If you don't see four parent records from the two above queries, then you have the answer to your problem. The solution of course is to not refer to records which do not exist.
I had to change The Foreign key reference for OrderID..it was referencing Orders (customerID) and it should be Reference Orders (OrderID)
CREATE TABLE OrderItem
( OrderID INT,
DonutID INT,
Qty SMALLINT not null,
PRIMARY KEY(OrderID, DonutID),
FOREIGN KEY (OrderID)
REFERENCES Orders (OrderID),
FOREIGN KEY (DonutID)
REFERENCES Donut (DonutID) ) ;
Answered my own question!

I get this error: Cannot add or update a child row: a foreign key constraint fails

I am trying to do inserts into my database to "populate" it, and all inserts work fine, except for the "reservation" insert...
When I try to insert my reservation table:
Insert Into Reservation
(ReservNum, ReserveDate, NumOfPassengers, sheduledTime, ActualPickupTime, ActualTime, PricePaid, HourlyRate, SalaryEarned)
VALUES
('24333', '2015-10-15', '6', '20', '7:04', '22', '$15', '34', '$12.47');
I get this error:
Cannot add or update a child row: a foreign key constraint fails (`oma`.`Reservation`, CONSTRAINT `Reservation_ibfk_1` FOREIGN KEY (`Customer_CustomerID`) REFERENCES `Customer` (`CustomerID`))
Here are my create tables:
CREATE TABLE Customer (
CustomerID INT AUTO_INCREMENT,
Name VARCHAR(90) NOT NULL,
Phone VARCHAR(45) NULL,
PRIMARY KEY (CustomerID));
CREATE TABLE Location (
Address VARCHAR(100) NOT NULL,
Latitude VARCHAR(45) NOT NULL DEFAULT ' ',
Longitude VARCHAR(45) NOT NULL,
PRIMARY KEY (Address));
CREATE TABLE Employee (
EmployeeID INT AUTO_INCREMENT,
Name VARCHAR(90) NOT NULL,
PRIMARY KEY (EmployeeID));
CREATE TABLE Truck (
LicensePlate CHAR(20) NOT NULL,
color VARCHAR(45) NULL,
capacity VARCHAR(45) NULL,
PRIMARY KEY (LicensePlate));
CREATE TABLE Shifts (
ShiftTime DATETIME NOT NULL,
PRIMARY KEY (ShiftTime));
CREATE TABLE EmployeeShifts (
DesiredShift DATETIME NOT NULL,
EmployeeWorking INT NULL,
DateOfShift DATE,
PRIMARY KEY(DesiredShift, EmployeeWorking),
FOREIGN KEY (EmployeeWorking) REFERENCES Employee(EmployeeID),
FOREIGN KEY (DesiredShift) REFERENCES Shifts(ShiftTime));
CREATE TABLE Reservation (
ReservNum INT NOT NULL,
ReserveDate DATE NULL,
PickupTime VARCHAR(45) NOT NULL,
NumOfPassengers INT NULL,
sheduledTime VARCHAR(45) NULL,
ActualPickupTime VARCHAR(45),
ActualTime VARCHAR(45),
SalaryEarned VARCHAR(10),
PricePaid VARCHAR(45),
HourlyRate DECIMAL(7,2) NOT NULL,
Customer_CustomerID INT AUTO_INCREMENT,
Truck_LicensePlate char(20) NOT NULL,
Employee_EmployeeID_Driver INT,
Location_Address_Pickup VARCHAR(100),
Employee_EmployeeID_Passenger INT,
Location_Address_Drop VARCHAR(100),
PRIMARY KEY (ReservNum),
FOREIGN KEY (Customer_CustomerID) REFERENCES Customer (CustomerID),
FOREIGN KEY (Truck_LicensePlate) REFERENCES Truck (LicensePlate),
FOREIGN KEY (Employee_EmployeeID_Driver) REFERENCES Employee (EmployeeID),
FOREIGN KEY (Location_Address_Pickup) REFERENCES Location (Address),
FOREIGN KEY (Employee_EmployeeID_Passenger) REFERENCES Employee (EmployeeID),
FOREIGN KEY (Location_Address_Drop) REFERENCES Location (Address));
The Customer_Customer_ID column in Reservation is an AUTO INCREMENT:
Customer_CustomerID INT AUTO_INCREMENT,
meaning that if you don't specify the value when INSERT-ing, one will be automatically assigned to it. You didn't specify it in the INSERT and so the value automatically assigned to it didn't exist in the Customers table, which violated the FOREIGN KEY constraint:
FOREIGN KEY (Customer_CustomerID) REFERENCES Customer (CustomerID),
To solve this,
Remove the AUTO_INCREMENT from the Customer_CustomerID column. You should be able to insert now, since the column can be NULL, in which case the FOREIGN KEY is not an issue.
Or, if you want to assign a Customer to the Reservation, make sure a row exists in the Customer table, and pass the Customer_Id to the INSERT INTO Reservation. For instance, like this:
INSERT INTO Customers( Name ) VALUES ('Test');
INSERT INTO Reservation (
ReservNum, Customer_Customer_ID,
ReserveDate, NumOfPassengers,
sheduledTime, ActualPickupTime, ActualTime,
PricePaid, HourlyRate, SalaryEarned
)
VALUES (
'24333', LAST_INSERT_ID(),
'2015-10-15', '6',
'20', '7:04', '22',
'$15', '34', '$12.47'
);
The LAST_INSERT_ID() gets the value from the AUTO_INCREMENT column in the last INSERT.

MySQL: Creating a table that with a foreign key that references a primary key made up of foreign keys

I have a table of books, which stores book IDs and titles, authors, etc., a table of customers which has customer IDs (PK), customer name, birthday. Then there is a table of transactions, which includes the BookId and the CustomerID as foreign keys. The primary key of this transaction table is the two foreign key columns.
The problem is now I am creating a table of book ratings based on transactions which have occurred (So a customer can't rate a book they don't own, or the same book twice.). This table must contain the bookID, the customerID, and the rating info. I'm trying to constrain the table so that each bookID and customerID row must reference an existing row in the transaction table. However, none of the constraints I've tried so far work. Any help at all would be greatly appreciated.
Here's my tables at the moment:
CREATE TABLE eBook
( BookTitle VARCHAR(50),
BookID CHAR(13) NOT NULL,
BookPub CHAR(4) NOT NULL,
BookDate DATE NOT NULL,
BookHard BOOL NOT NULL,
BookSize INT NOT NULL,
CONSTRAINT PKBookID PRIMARY KEY (BookID)
);
CREATE TABLE customer
( CustID CHAR(9) NOT NULL,
CustSSN CHAR(11) NULL,
CustName VARCHAR(50) NOT NULL,
CustBirth INT(4) NOT NULL,
CONSTRAINT PKCustID PRIMARY KEY (CustID),
CONSTRAINT UniqSSN UNIQUE (CustSSN)
);
CREATE TABLE Buys
( BuysID CHAR(5) NOT NULL
BookID CHAR(13) NOT NULL,
CustID CHAR(9) NOT NULL,
TransDate DATETIME NOT NULL,
Price DECIMAL(5,2) NOT NULL,
CONSTRAINT FK1 FOREIGN KEY (BookID) REFERENCES eBook (BookID)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT FK2 FOREIGN KEY (CustID) REFERENCES customer (CustID)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT PKBuys PRIMARY KEY (BookID, CustID)
);
CREATE TABLE Rating
( BookID CHAR(13) NOT NULL,
CustID CHAR(9) NOT NULL,
RatingID CHAR(5) NOT NULL,
Rating INT(1) NOT NULL,
RatingDate DATE NOT NULL,
CONSTRAINT FK13 FOREIGN KEY (BookID, CustID) REFERENCES buys (BookID, CustID)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT PKRating PRIMARY KEY (RatingID)
);
You already have a foreign key on your Rating table that should constrain Rating rows each to correspond to a Buys row. I suppose that the problem must be with your other objective, that customers cannot rate the same book twice. With respect to that, I guess you have a misconception about foreign keys: they have to be unique on the target table, but they do not automatically have to be unique on the referring side.
To prevent multiple Rating rows having the same combination of BookID and CustomerID, you need an additional UNIQUE constraint on the Rating table, naming those columns. Alternatively, you could give the Rating table a composite primary key consisting of those columns. Either way, you'll have separate constraints, one establishing the uniqueness of those columns in the referring table, and the other constraining them to pairs that appear in the Buys table.
You can create a multi column foreign key reference as documented on http://dev.mysql.com/doc/refman/5.0/en/create-table-foreign-keys.html
That should do the trick.
Your sample code contains an error. You are missing a (,) in the Buys table.
CREATE TABLE eBook
( BookTitle VARCHAR(50),
BookID CHAR(13) NOT NULL,
BookPub CHAR(4) NOT NULL,
BookDate DATE NOT NULL,
BookHard BOOL NOT NULL,
BookSize INT NOT NULL,
CONSTRAINT PKBookID PRIMARY KEY (BookID)
);
CREATE TABLE customer
( CustID CHAR(9) NOT NULL,
CustSSN CHAR(11) NULL,
CustName VARCHAR(50) NOT NULL,
CustBirth INT(4) NOT NULL,
CONSTRAINT PKCustID PRIMARY KEY (CustID),
CONSTRAINT UniqSSN UNIQUE (CustSSN)
);
CREATE TABLE Buys
( BuysID CHAR(5) NOT NULL,
BookID CHAR(13) NOT NULL,
CustID CHAR(9) NOT NULL,
TransDate DATETIME NOT NULL,
Price DECIMAL(5,2) NOT NULL,
CONSTRAINT FK1 FOREIGN KEY (BookID) REFERENCES eBook (BookID)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT FK2 FOREIGN KEY (CustID) REFERENCES customer (CustID)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT PKBuys PRIMARY KEY (BookID, CustID)
);
CREATE TABLE Rating
( BookID CHAR(13) NOT NULL,
CustID CHAR(9) NOT NULL,
Rating INT(1) NOT NULL,
RatingDate DATE NOT NULL,
CONSTRAINT FK13 FOREIGN KEY (BookID, CustID) REFERENCES buys (BookID, CustID)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT PKRating PRIMARY KEY (BookID, CustID)
);
When using this corrected ddl, the tables are created just fine.
I've created some test data
insert into `ebook`(`BookTitle`,`BookID`,`BookPub`,`BookDate`,`BookHard`,`BookSize`) values ('grey','1','ME','2015-02-06',1,10);
insert into `customer`(`CustID`,`CustSSN`,`CustName`,`CustBirth`) values ('1','daCust','Cust',1974);
insert into `buys`(`BuysID`,`BookID`,`CustID`,`TransDate`,`Price`) values ('1','1','1','2015-02-06 00:00:00',10.00);
insert into `rating`(`BookID`,`CustID`,`RatingID`,`Rating`,`RatingDate`) values ('1','1','1',1,'2015-02-06');
Now adding the following data will result in an error due to the foreign key constraint.
insert into `rating`(`BookID`,`CustID`,`RatingID`,`Rating`,`RatingDate`) values ('7','3','1',1,'2015-02-06');
To ensure that the user can add only one rating per book you should add a unique constraint on the fields BookID and CustID or set those fields as primary key. In the working code example above i have added those fields as primary key and removed the obsolete RatingID.