ERROR 1451 Cannot delete a record from parent table - mysql

Hey guys so im trying to delete a record. However doesnt allow me due to a foreign key constraint
Operation im trying to perform is
(all cards numbers are fake)
DELETE FROM payment_method
WHERE card_no = 42218345;
table structures:
CREATE TABLE payment_details (
card_no int(8) NOT NULL,
customer_id int(50) NOT NULL AUTO_INCREMENT,
CVV int(3) NOT NULL,
card_type ENUM ('Visa', 'Amex', 'American Express', 'Mastercard') NOT NULL,
expiry_date DATE NOT NULL,
PRIMARY KEY(card_no),
KEY customer_idfk1 (customer_id),
CONSTRAINT customer_idfk1 FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
and
CREATE TABLE customers (
customer_id int(50) NOT NULL AUTO_INCREMENT,
fname varchar(20) NOT NULL,
lname varchar(20) NOT NULL,
dateOfBirth date NOT NULL,
address varchar(30) NOT NULL,
city varchar(20) NOT NULL,
county ENUM('Armagh','Carlow','Cavan','Clare','Cork','Derry','Donegal','Down','Dublin','Fermanagh','Galway','Kerry','Kildare','Kilkenny','Laois','Leitrim','Limerick','Longford','Louth','Mayo','Meath','Monaghan','Offaly','Roscommon','Sligo','Tipperary','Tyrone','Waterford','Westmeath','Wexford','Wicklow') NOT NULL,
phone int(10) NOT NULL,
email varchar(20) NOT NULL,
payment_method ENUM ('Visa', 'Amex', 'Cash', 'American Express', 'Mastercard') NOT NULL,
valid_licence varchar(5) NOT NULL,
status varchar(10),
PRIMARY KEY (customer_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
error is:
1451 - Cannot delete or update a parent row: a foreign key constraint fails (g00337857abu.payment_details, CONSTRAINT customer_idfk1
FOREIGN KEY (customer_id) REFERENCES customers (customer_id))
Does anyone know Why it doesnt allow me to delete this record..
Ive spotted 1st error
Now im trying to delete from customers table
DELETE FROM customers
WHERE customer_id = 1
error - #1451 - Cannot delete or update a parent row: a foreign key
constraint fails (g00337857abu.payment_details, CONSTRAINT
customer_idfk1 FOREIGN KEY (customer_id) REFERENCES customers
(customer_id))

Related

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

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));

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!

MYSQL: Error Code: 1215. Cannot add foreign key constraint

basically I have an issue with creating a joined table and don't know how to fix it. I created cInfo first, then mInfo, then eInfo which all worked but then when trying to create cRented it gave me the error: Error Code: 1215. Cannot add foreign key constraint. Any help?
Here is the code:
CREATE TABLE cInfo (
cid int(4) DEFAULT '0',
fname varchar(20) NOT NULL,
sname varchar(20) NOT NULL,
age int(4) DEFAULT '0',
gender enum('M', 'F') NOT NULL DEFAULT 'M',
telno int(10) DEFAULT '0',
email varchar(20) NOT NULL,
addr varchar(50) NOT NULL,
cowed int(4) NOT NULL DEFAULT '0',
PRIMARY KEY (cid, cowed)
);
INSERT INTO cInfo VALUES(1,'Smith', 'John', 20, 'M', 0891234567,
'smith.john#gmail.com', '1 Bishopstown Road, Cork', 10);
CREATE TABLE mInfo (
mid INT NOT NULL,
title varchar(100) NOT NULL,
director varchar(100) NOT NULL,
relyear int(4) NOT NULL,
genre enum('Thriller','Horror','Documentary','Comedy','Drama') NOT NULL
DEFAULT ‘Drama’,
PRIMARY KEY (mid)
);
INSERT INTO mInfo VALUES(1,'Justice League', 'Zack Snyder', 2017, 'Comedy');
CREATE TABLE eInfo (
eid int(4) DEFAULT '0',
ppsn varchar(10) NOT NULL,
fname varchar(20) NOT NULL,
sname varchar(20) NOT NULL,
gender enum(‘M’, ‘F’) NOT NULL DEFAULT ‘M’,
telno int(10) DEFAULT '0',
email varchar(100) NOT NULL,
addr varchar(200) NOT NULL,
mid INT NOT NULL,
PRIMARY KEY (mid),
CONSTRAINT eInfo_ref1 FOREIGN KEY (mid) REFERENCES mInfo (mid)
);
INSERT INTO eInfo VALUES(1, '1234567A', 'Moyes', 'Richard', 'M', 0871234567,
'moyes.richard#gmail.com', '1 CIT Road, Cork', 1 );
CREATE TABLE cRented (
cid int(4) DEFAULT '0',
mid INT NOT NULL,
dor Date NOT NULL,
cowed int(4) NOT NULL DEFAULT '0',
PRIMARY KEY (cid, mid, cowed),
CONSTRAINT cRented_ref1 FOREIGN KEY (cid) REFERENCES cInfo (cid),
CONSTRAINT cRented_ref2 FOREIGN KEY (mid) REFERENCES mInfo (mid),
CONSTRAINT cRented_ref3 FOREIGN KEY (cowed) REFERENCES cInfo (cowed)
);
INSERT INTO cRented VALUES(1, 1, 2017-11-23, 10 );
In the following:
CONSTRAINT cRented_ref1 FOREIGN KEY (cid) REFERENCES cInfo (cid),
CONSTRAINT cRented_ref2 FOREIGN KEY (mid) REFERENCES mInfo (mid),
CONSTRAINT cRented_ref3 FOREIGN KEY (cowed) REFERENCES cInfo (cowed)
remove CONSTRAINT cRented_ref3 in favor of composite foreign key cRented_ref1:
CONSTRAINT cRented_ref1 FOREIGN KEY (cid, cowed) REFERENCES cInfo (cid, cowed),
CONSTRAINT cRented_ref2 FOREIGN KEY (mid) REFERENCES mInfo (mid)
That way cRented_ref1 matches the composite primary key on cInfo.
Table eInfo is not likely an issue in this case though making the primary key and foreign key constraints the same column implies a 1:1 relationship between the data in eInfo and mInfo.

Mysql code runs but the foreign key values are not showing in table in phpmyadmin

My code runs in phpmyadmin but the foreign key values are not showing in table and when I update it the message shows "0 rows affected"
my table schema is:
CREATE TABLE fee_report (
fr_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
school_id INT NOT NULL,
branch_id INT NOT NULL,
student_id INT NOT NULL,
ledger VARCHAR(55),
bill_no VARCHAR(255) NOT NULL,
fdate date NOT NULL,
receipt_no VARCHAR(255) NOT NULL,
dr float NOT NULL,
cr float NOT NULL,
balance float NOT NULL,
particulars VARCHAR(155),
updated TIMESTAMP NOT NULL,
CONSTRAINT fk_frschool FOREIGN KEY (school_id)
REFERENCES school(school_id),
CONSTRAINT fk_frbranch FOREIGN KEY (branch_id)
REFERENCES branch(branch_id),
CONSTRAINT fk_frstudent FOREIGN KEY (student_id)
REFERENCES student(student_id)
) ENGINE = INNODB;
INSERT INTO fee_report(school_id,branch_id,student_id,ledger,bill_no,fdate,dr,balance,particulars,feetype)
VALUES(1,1,13,'TGS007','SESNOV1020',CURDATE(),'2850','-14450','11','Tuition Fee,Transport Fee,Smart Class Fee,SA-1 Exam Fee')
Why foreign keys school_id, branch_id and student_id are not showing in table
and when I remove foreign key constraint the values are visible in table

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.