SQL Error Code: 1452 when inserting data into table with FK referring to another table - mysql

I am currently trying to populate my tables with data via a SQL script and have been having issues getting my FKs cooperate while populating my book table. I've read the other threads on the issue and have tried ON DELETE CASCADE and the other suggestions of populating the FKs first didn't work for me either. I also saw you can override the FK check however that seems counterproductive to making a working database.
I've attached my scripts and create.sql runs fine but insert.sql as I said gets stuck on the last command.
Thanks for your time!
-----
create.sql
-----
CREATE TABLE Dept (
Dept_ID INT(2) NOT NULL,
Dept_Name CHAR(16) NOT NULL,
Dept_Floor INT(1) NOT NULL,
PRIMARY KEY (Dept_ID)
);
CREATE TABLE Publisher (
Publisher_Name VARCHAR(50) NOT NULL,
PubAddress VARCHAR(20) NOT NULL,
Phone_Number VARCHAR(15) NOT NULL,
PRIMARY KEY (Publisher_Name)
);
CREATE TABLE Book (
Book_ID INT(6) NOT NULL,
Title VARCHAR(32) NOT NULL,
Dept_ID INT(2),
Publisher_Name VARCHAR(20),
PRIMARY KEY (Book_ID),
FOREIGN KEY (Dept_ID) REFERENCES Dept(Dept_ID),
FOREIGN KEY (Publisher_Name) REFERENCES Publisher(Publisher_Name)
);
-----
insert.sql
-----
INSERT INTO Dept (Dept_ID, Dept_Name, Dept_Floor)
VALUES ('01', 'Fantasy', '1'), ('02', 'Sci-Fi', '1'), ('03', 'Fiction', '2'), ('04', 'Educational', '1'), ('05', 'Crime', '2');
INSERT INTO Publisher (Publisher_Name, PubAddress, Phone_Number)
VALUES ('Bloomsbury', '234 Hay Street', '14325673489'), ('Charles Scribner','236 Hone Way','173677654765'),('Pigeon Books','5444 North Street','17884787644'), ('Academic Press', '2354 Bridge Road', '175634598234'), ('Bantam Books', '2623 River Road', '17234648444');
INSERT INTO Book (Book_ID, Title, Dept_ID, Publisher_Name)
VALUES ('000001','Harry Potter and the Goblet of Fire', '01', 'Bloomsbury'), ('000002','A Brief History of Time', '04', 'Puffin Books'), ('000003','The Great Gatsby', 'Charles Scribners Sons', '03'), ('000004','Advances in Ecological Research', 'Academic Press', '04'), ('000005','The Case of Joe', 'Bantam Books', '05');

Your columns are not aligned and your data length is too small for your given data.
CREATE TABLE Dept (
Dept_ID INT(2) NOT NULL,
Dept_Name CHAR(16) NOT NULL,
Dept_Floor INT(1) NOT NULL,
PRIMARY KEY (Dept_ID)
);
CREATE TABLE Publisher (
Publisher_Name VARCHAR(50) NOT NULL,
PubAddress VARCHAR(20) NOT NULL,
Phone_Number VARCHAR(15) NOT NULL,
PRIMARY KEY (Publisher_Name)
);
CREATE TABLE Book (
Book_ID INT(6) NOT NULL,
Title VARCHAR(40) NOT NULL,
Dept_ID INT(2),
Publisher_Name VARCHAR(50),
PRIMARY KEY (Book_ID),
FOREIGN KEY (Dept_ID) REFERENCES Dept(Dept_ID),
FOREIGN KEY (Publisher_Name) REFERENCES Publisher(Publisher_Name)
);
INSERT INTO Dept (Dept_ID, Dept_Name, Dept_Floor)
VALUES ('01', 'Fantasy', '1'), ('02', 'Sci-Fi', '1'), ('03', 'Fiction', '2'), ('04', 'Educational', '1'), ('05', 'Crime', '2');
INSERT INTO Publisher (Publisher_Name, PubAddress, Phone_Number)
VALUES ('Bloomsbury', '234 Hay Street', '14325673489'), ('Charles Scribner','236 Hone Way','173677654765'),('Pigeon Books','5444 North Street','17884787644'), ('Academic Press', '2354 Bridge Road', '175634598234'), ('Bantam Books', '2623 River Road', '17234648444');
INSERT INTO Book (Book_ID, Title, Dept_ID, Publisher_Name)
VALUES ('000001','Harry Potter and the Goblet of Fire', '01', 'Bloomsbury'), ('000002','A Brief History of Time', '04', 'Bantam Books'), ('000003','The Great Gatsby', '03', 'Charles Scribner'), ('000004','Advances in Ecological Research', '04', 'Academic Press'), ('000005','The Case of Joe', '05', 'Bantam Books');

In your case, this error/failure means that the foreign key constraint is working correctly. The book insert is failing because you're trying to insert a book with a publisher that doesn't exist. Two of them, in fact:
('000003','The Great Gatsby', 'Charles Scribners Sons', '03')
You don't have "Charles Scribners Sons" publisher, only "Charles Scribner".
('000002','A Brief History of Time', '04', 'Puffin Books'),
You don't have Puffin Books publisher, only Pigeon Books.
Also, your book records are wrong, the last two of them. They've got Publisher name, then Dept ID...
In short, this is precisely the case when precisely this error should occur, because your data is malformed.

Create.sql and insert.sql both having data size and ordering issue.
I just corrected your query and now it will work fine for you.
---create.sql----
CREATE TABLE Dept (
Dept_ID INT NOT NULL
,Dept_Name CHAR(16) NOT NULL
,Dept_Floor INT NOT NULL
,PRIMARY KEY (Dept_ID)
);
CREATE TABLE Publisher (
Publisher_Name VARCHAR(50) NOT NULL
,PubAddress VARCHAR(20) NOT NULL
,Phone_Number VARCHAR(15) NOT NULL
,PRIMARY KEY (Publisher_Name)
);
CREATE TABLE Book (
Book_ID INT NOT NULL
,Title VARCHAR(50) NOT NULL
,Dept_ID INT
,Publisher_Name VARCHAR(50)
,PRIMARY KEY (Book_ID)
,FOREIGN KEY (Dept_ID) REFERENCES Dept(Dept_ID)
,FOREIGN KEY (Publisher_Name) REFERENCES Publisher(Publisher_Name)
);
---insert.sql---
INSERT INTO Dept (Dept_ID, Dept_Name, Dept_Floor)
VALUES ('01', 'Fantasy', '1'), ('02', 'Sci-Fi', '1'), ('03', 'Fiction', '2'), ('04', 'Educational', '1'), ('05', 'Crime', '2');
INSERT INTO Publisher (Publisher_Name, PubAddress, Phone_Number)
VALUES ('Bloomsbury', '234 Hay Street', '14325673489'), ('Charles Scribner','236 Hone Way','173677654765'),('Pigeon Books','5444 North Street','17884787644'), ('Academic Press', '2354 Bridge Road', '175634598234'), ('Bantam Books', '2623 River Road', '17234648444');
INSERT INTO Book (Book_ID, Title, Dept_ID, Publisher_Name)
VALUES ('000001','Harry Potter and the Goblet of Fire', '01', 'Bloomsbury'), ('000002','A Brief History of Time', '04', 'Charles Scribner'), ('000003','The Great Gatsby', '03','Pigeon Books'), ('000004','Advances in Ecological Research', '04','Academic Press'), ('000005','The Case of Joe', '05','Bantam Books' );

Related

How can I have both receptionist name and doctors name in the same Query output?

Generate a list of all appointments in alphabetical order by patient name and by latest date and time for each patient. The list should also include the doctor scheduled and the receptionist who made the appointment.
This is my query so far:
SELECT PatientLastName, PatientFirstName, Date_Time AS 'AppointmentTime', ReasonForAppointment,
EmployeeLastName AS 'DoctorLastName', EmployeeFirstName AS 'DoctorFirstName', D.Speciality,
EmployeeLastName AS 'ReceptionistLastName', EmployeeFirstName AS 'ReceptionistFirstName'
FROM Employee_T E JOIN Doctor_T D ON E.EmployeeID = D.Doctor_ID
JOIN Appointment_T A ON D.Doctor_ID = A.Doctor_ID JOIN Patient_T P ON A.Patient_ID = P.Patient_ID
ORDER BY Date_Time DESC;
Here are my create table statements:
CREATE TABLE Employee_T
(EmployeeID DECIMAL(11,0) NOT NULL,
EmployeeFirstName VARCHAR(25),
EmployeeLastName VARCHAR(25),
EmployeeStreet VARCHAR(30),
EmployeeCity VARCHAR(20),
EmployeeState CHAR(2),
EmployeeZipCode VARCHAR(16),
EmployeeHireDate DATE,
EmployeeEmail VARCHAR(25),
EmployeePhone VARCHAR(14),
EmployeeType VARCHAR(1),
CONSTRAINT Employee_PK PRIMARY KEY (EmployeeID));
CREATE TABLE Doctor_T
(Doctor_ID DECIMAL(11,0) NOT NULL,
Speciality VARCHAR(30),
Degree VARCHAR(40),
College VARCHAR(50),
CertificationDate Date,
CONSTRAINT Doctor_PK PRIMARY KEY (Doctor_ID),
CONSTRAINT Docter_FK1 FOREIGN KEY (Doctor_ID) REFERENCES Employee_T(EmployeeID));
CREATE TABLE Nurse_T
(Nurse_ID DECIMAL(11,0) NOT NULL,
Speciality VARCHAR(30),
Degree VARCHAR(30),
College VARCHAR(40),
CertificationDate Date,
CONSTRAINT Nurse_PK PRIMARY KEY (Nurse_ID),
CONSTRAINT Nurse_FK1 FOREIGN KEY (Nurse_ID) REFERENCES Employee_T(EmployeeID));
CREATE TABLE Receptionist_T
(Receptionist_ID DECIMAL(11,0) NOT NULL,
Languages VARCHAR(30),
YearsOfExperience VARCHAR(30),
Assigned_Doctor_ID DECIMAL(11,0) NOT NULL,
CONSTRAINT Receptionist_PK PRIMARY KEY (Receptionist_ID),
CONSTRAINT Receptionist_FK1 FOREIGN KEY (Receptionist_ID) REFERENCES Employee_T(EmployeeID),
CONSTRAINT Receptionist_FK2 FOREIGN KEY (Assigned_Doctor_ID) REFERENCES Doctor_T (Doctor_ID));
CREATE TABLE Patient_T
(Patient_ID DECIMAL(11,0) NOT NULL,
PatientFirstName VARCHAR(25),
PatientLastName VARCHAR(25),
PatientStreet VARCHAR(30),
PatientCity VARCHAR(20),
PatientState CHAR(2),
PatientZipCode VARCHAR(16),
PatientEmail VARCHAR(25),
PatientPhone VARCHAR(14),
CONSTRAINT Patient_PK PRIMARY KEY (Patient_ID));
CREATE TABLE Appointment_T
(Appointment_ID DECIMAL(11,0) NOT NULL,
Date_Time DATETIME,
Cost VARCHAR(30),
ReasonForAppointment VARCHAR(30),
Patient_ID DECIMAL(11,0) NOT NULL,
Receptionist_ID DECIMAL(11,0) NOT NULL,
Doctor_ID DECIMAL(11,0) NOT NULL,
CONSTRAINT Appointment_PK PRIMARY KEY (Appointment_ID),
CONSTRAINT Appointment_FK1 FOREIGN KEY (Patient_ID) REFERENCES Patient_T(Patient_ID),
CONSTRAINT Appointment_FK2 FOREIGN KEY (Receptionist_ID) REFERENCES Receptionist_T(Receptionist_ID),
CONSTRAINT Appointment_FK3 FOREIGN KEY (Doctor_ID) REFERENCES Doctor_T (Doctor_ID));
CREATE TABLE Treatment_T
(Treatment_ID DECIMAL(11,0) NOT NULL,
Date_Time DATETIME,
TreatmentDescription VARCHAR(100),
Patient_ID DECIMAL(11,0) NOT NULL,
Nurse_ID DECIMAL(11,0) NOT NULL,
Doctor_ID DECIMAL(11,0) NOT NULL,
CONSTRAINT Treatment_PK PRIMARY KEY (Treatment_ID),
CONSTRAINT Treatment_FK1 FOREIGN KEY (Patient_ID) REFERENCES Patient_T (Patient_ID),
CONSTRAINT Treatment_FK2 FOREIGN KEY (Nurse_ID) REFERENCES Nurse_T(Nurse_ID),
CONSTRAINT Treatment_FK3 FOREIGN KEY (Doctor_ID) REFERENCES Doctor_T(Doctor_ID));
-- Create tables above the line - load tables below this line - DON't MIX
INSERT INTO Employee_T (EmployeeID, EmployeeFirstName, EmployeeLastName, EmployeeStreet, EmployeeCity, EmployeeState, EmployeeZipCode, EmployeeHireDate, EmployeeEmail, EmployeePhone, EmployeeType)
VALUES
(1, 'Nicole', 'Blundell', '38 San Pablo St.', 'HydePark', 'MA', '02136', '2000-01-18', 'gfody#yahoo.com', '501-971-6249', 'D'),
(2, 'Aaminah', 'Greaves', '682 Homestead Avenue', 'Waterloo', 'IA', '50701', '1999-02-20', 'noahb#yahoo.com', '374-695-6935', 'D'),
(3, 'Donnie', 'Mitchell', '20 Winding Way Ave.', 'Philadelphia', 'PA', '19111', '2003-04-20', 'tubesteak#sbcglobal.net', '702-492-7923', 'D'),
(4, 'Maximilian', 'Knox', '8541 Lincoln St.', 'North Canton', 'OH', '44720', '2007-03-08', 'cremonini#msn.com', '532-913-3370', 'N'),
(5, 'Mayur', 'Howarth', '890 Clark Drive', 'Cranberry Twp', 'PA', '16066', '2006-05-12', 'meinkej#optonline.net', '521-455-8032', 'N'),
(6, 'Brenna', 'Huerta', '8 Mayfair St.', 'Indiana', 'PA', '15701', '2012-06-16', 'raines#live.com', '503-325-8968', 'N'),
(7, 'Kwabena', 'Childs', '935 Miller Avenue', 'Detroit', 'MI', '48205', '2002-04-24', 'eidac#mac.com', '686-212-1659', 'N'),
(8, 'Jamie-Lee', 'Weir', '52 Brickyard Ave.', 'Glastonbury', 'CT', '06033', '2008-07-30', 'gospodin#mac.com', '374-940-2173', 'R'),
(9, 'Kade', 'Peters', '7035 Dunbar St.', 'Lynchburg', 'VA', '24502', '2009-06-14', 'delpino#verizon.net', '688-957-6625', 'R'),
(10, 'Rosalie', 'Piper', '845 E. Rockwell Ave.', 'Winter Park', 'FL', '32792', '2016-05-24', 'ideguy#aol.com', '522-917-8366', 'R'),
(11, 'Tyler-Jay', 'Kaufman', '631 North Joy Ridge St.', 'Saint Paul', 'MN', '55104', '2018-08-25', 'dalamb#yahoo.ca', '433-584-5674', 'R');
INSERT INTO Doctor_T (Doctor_ID, Speciality, Degree, College, CertificationDate)
VALUES
(1, 'Anesthesiology', 'Doctor Osteopathic Medicine', 'Harvard Medical School', '1990-03-16'),
(2, 'Neurosurgeon', 'Doctor Osteopathic Medicine', 'Baylor College of Medicine', '1995-05-20'),
(3, 'Transplant Surgeon', 'Doctor Osteopathic Medicine', 'Eastern Virginia Medical School', '2000-05-12');
INSERT INTO Nurse_T (Nurse_ID, Speciality, Degree, College, CertificationDate)
VALUES
(4,'Cardiac Nurse', 'Bachelor of Science In Nursing', 'Harvard Medical School', '2002-05-13'),
(5,'Critical Care Nurse', 'Bachelor of Science In Nursing', 'Perelman School of Medicine', '2003-04-13'),
(6,'ER Nurse', 'Bachelor of Science In Nursing', 'Boston University School of Medicine', '2010-02-12'),
(7,'Nursing Administrator', 'Bachelor of Science In Nursing', 'Mayo Clinic Alix School of Medicine', '2000-02-10');
INSERT INTO Receptionist_T (Receptionist_ID, Languages, YearsOfExperience, Assigned_Doctor_ID)
VALUES
(8,'Japanese', '4', '1'),
(9,'English', '6', '2'),
(10,'Spanish', '7', '3'),
(11,'Chinese', '9', '1');
INSERT INTO Patient_T (Patient_ID, PatientFirstName, PatientLastName, PatientStreet, PatientCity, PatientState, PatientZipCode, PatientEmail, PatientPhone)
VALUES
('301', 'Katerina', 'Lutz', '739 Lafayette St.', 'Ocean Springs', 'MS', '39564', 'psharpe#aol.com', '317-433-6415'),
('302', 'Joel', 'Morrow', '83 Spruce St.', 'Petersburg', 'VA', '23803', 'yzheng#me.com', '487-656-3992'),
('303', 'Arian', 'Bowler', '9475 Roberts Road', 'Bay City', 'MI', '48706', 'jmgomez#live.com', '433-915-0426'),
('304', 'Taryn', 'Ali', '9337 Windsor St.', 'Coachella', 'CA', '92236', 'okroeger#verizon.net', '597-399-1799');
INSERT INTO Appointment_T (Appointment_ID, Date_Time, Cost, ReasonForAppointment, Patient_ID, Receptionist_ID, Doctor_ID)
VALUES
('621', '2020-04-12 08:00:10', '$150', 'Leg X-Ray', '301', '8', '1'),
('622', '2020-08-18 10:00:05', '$110', 'Fever', '302', '9', '2'),
('623', '2020-05-30 11:00:13', '$100', 'Chest Pain', '303', '10', '3'),
('624', '2020-06-22 16:00:17', '$150', 'Chronic Pain', '304', '11', '1'),
('625', '2020-08-09 13:00:09', '$150', 'Blurred Vision', '301', '9', '3'),
('626', '2020-10-20 15:00:12', '$150', 'Ringing In Ears', '302', '8', '3');
INSERT INTO Treatment_T (Treatment_ID, Date_Time, TreatmentDescription, Patient_ID, Nurse_ID, Doctor_ID)
VALUES
('731', '2020-04-20 12:00:08', 'Wear brace to treat injured leg', '301', '5', '1'),
('732', '2020-08-21 14:00:06', 'Drink cough medicine once a day', '302', '7', '2'),
('733', '2020-06-02 17:00:09', 'Take Acetaminophen medicne to treat chest pain', '303', '5', '3');
SELECT * FROM Employee_T;
SELECT * FROM Doctor_T;
SELECT * FROM Nurse_T;
SELECT * FROM Receptionist_T;
SELECT * FROM Patient_T;
SELECT * FROM Appointment_T;
SELECT * FROM Treatment_T;
You need to join to the Employee_T table twice, once to fetch the doctor's name, and once to fetch the receptionist's name:
SELECT P.PatientLastName,
P.PatientFirstName,
A.Date_Time AS 'AppointmentTime',
A.ReasonForAppointment,
ED.EmployeeLastName AS 'DoctorLastName',
ED.EmployeeFirstName AS 'DoctorFirstName',
D.Speciality,
ER.EmployeeLastName AS 'ReceptionistLastName',
ER.EmployeeFirstName AS 'ReceptionistFirstName'
FROM Appointment_T A
JOIN Patient_T P ON A.Patient_ID = P.Patient_ID
JOIN Doctor_T D ON D.Doctor_ID = A.Doctor_ID
JOIN Employee_T ED ON ED.EmployeeID = D.Doctor_ID
JOIN Employee_T ER ON ER.EmployeeID = A.Receptionist_ID
ORDER BY Date_Time DESC
Output (for your sample data):
PatientLastName PatientFirstName AppointmentTime ReasonForAppointment DoctorLastName DoctorFirstName Speciality ReceptionistLastName ReceptionistFirstName
Morrow Joel 2020-10-20 15:00:12 Ringing In Ears Mitchell Donnie Transplant Surgeon Weir Jamie-Lee
Morrow Joel 2020-08-18 10:00:05 Fever Greaves Aaminah Neurosurgeon Peters Kade
Lutz Katerina 2020-08-09 13:00:09 Blurred Vision Mitchell Donnie Transplant Surgeon Peters Kade
Ali Taryn 2020-06-22 16:00:17 Chronic Pain Blundell Nicole Anesthesiology Kaufman Tyler-Jay
Bowler Arian 2020-05-30 11:00:13 Chest Pain Mitchell Donnie Transplant Surgeon Piper Rosalie
Lutz Katerina 2020-04-12 08:00:10 Leg X-Ray Blundell Nicole Anesthesiology Weir Jamie-Lee
Demo on db-fiddle

The conflict occurred in database "

I have the code here, but it was written by my teachers
create database abc_quanlybanhang111111;
use abc_quanlybanhang111111;
create table abc_nhacc
(
MaCC1 varchar(10) primary key,
TenNhaCC varchar(50) not null,
DiaChiCC varchar(50),
PhoneCC varchar(11),
);
create table abc_mamh
(
MaMH1 varchar(50) primary key,
TenMH varchar(100),
DonGia int,
SoLuong int,
MaCC1 varchar(10) foreign key references abc_nhacc(MaCC1)
);
create table abc_khachhang
(
MaMh1 VARCHAR(10) PRIMARY KEY,
TenKh varchar(50),
DiaChi varchar(50),
SĐT int,
);
CREATE TABLE abc_donhang
(
MaDH1 varchar(10) primary key,
NgayDH DATE default GetDate(),
MaKH1 varchar(10) foreign key references abc_khachhang(MaMH1)
);
create table abc_chitietdonhang
(
MaDH1 varchar(10) foreign key references abc_donhang(MaDH1) ,
MaMH1 varchar(50) foreign key references abc_mamh(MaMH1),
SoLuong int check (soluong>0)
constraint pk_dmhh primary key ( MaDH1, MaMH1)
);
insert into abc_nhacc
values
('K001', 'THE GIOI DI DONG', '121 TRAN QUANG KHAI', '0164789720'),
('K002', 'NGUYEN KIM', '12 TRAN PHU', '0161792793'),
('K003', 'THIEN HOA', '2 BA HUYEN THANH QUAN', '094850873'),
('K004', 'PHONG VU', '32 LE VAN VIET QUAN 9', '85839201'),
('K005', 'TAN BINH', '14 NGUYEN THI DINH', '0912012901')
SELECT *
FROM abc_nhacc;
insert into abc_mamh
values
('S001', 'MSI ACER GAMING', 2000000, 1, 'K001');
insert into abc_mamh
values
('S002', 'MSI ASUS GAMING', 1000000, 10, 'K002'),
('S003', 'MSI GAMING', 1100000, 1, 'K003'),
('S004', 'LENOVO GAMING', 2000, 111, 'K004'),
('S005', 'IPHONE', 120000, 1, 'K005')
SELECT *
FROM abc_mamh;
insert into abc_khachhang
values
('KH1', 'LONG NGUYEN', '12 TRAN QUANG DIEU QUAN 1', '0938078972');
insert into abc_khachhang
values
('KH2', 'THONG NGUYEN', '1 TRAN DIEU QUAN 2', '0968071972'),
('KH3', 'THANH NGUYEN', '23 NGUYEN THI DINH QUAN 8', '0138073972'),
('KH4', 'THINH NGUYEN', '1 TRUONG DINH QUAN 1', '016479828'),
('KH5', 'LINH TRAN', '2 TRAN QUANG KHAI QUAN 1', '0938078122')
SELECT *
FROM abc_mamh;
insert into abc_chitietdonhang
values('DH001', 'MH001', 2),
('DH002', 'MH002', 3),
('DH003', 'MH003', 1),
('DH004', 'MH004', 9),
('DH004', 'MH005', 4),
('DH003', 'MH006', 11),
('DH001', 'MH007', 12);
I have try to fix the code with the step delete the foreign key but it always show errors after I delete it :
Msg 547, Level 16, State 0, Line 72
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__abc_chiti__MaDH1__4222D4EF". The conflict occurred in database "abc_quanlybanhang1111111", table "dbo.abc_donhang", column 'MaDH1'
Please help me learn how to can fix this errors. Thank.
You have to add the rows in abc_donhang which you are trying to reference in your insert into abc_chitietdonhang ... query. You try to reference the row with the Id DH001, but it doesn't exists (yet). Same goes for the Id MH001, it doesn't exists in the abc_mamh table either.

sql integrity constraint parent key not found

I am trying to do something so simple creating and insert 4 tables with their data. I have spent hours on the web researching integrity constraints and tried several IDE's in case there's a bug but nothing seems to work. Code is shows below (excuted in order).
I can insert the data for the first two tables i.e vod_actor and vod_classification but when trying to add third/fourth table data I get the following error:
ORA-02291: integrity constraint (SYSTEM.VOD_FILM_CLASS_FK) violated - parent
I don't understand why because the FK for vod_film is the PK for vod_classification which already has its data populated.
Any help would be greatly appreciated. I am a beginner please bear that in mind. Thanks
CREATE TABLE vod_actor (
dbActorId CHAR(4) NOT NULL,
dbFirstname VARCHAR2(50) NOT NULL,
dbLastname VARCHAR2(50) NOT NULL,
dbDateOfBirth DATE,
dbNationality VARCHAR2(30),
dbBiography CLOB,
CONSTRAINT vod_actor_PK PRIMARY KEY (dbActorId)
);
CREATE TABLE vod_classification (
dbClassId CHAR(4) NOT NULL,
dbDescription VARCHAR(250) NOT NULL,
CONSTRAINT vod_classification_PK PRIMARY KEY (dbClassId)
);
CREATE TABLE vod_film (
dbFilmId CHAR(4) NOT NULL,
dbTitle VARCHAR2(100) NOT NULL,
dbDirector_firstname VARCHAR2(50) NOT NULL,
dbDirector_lastname VARCHAR2(50) NOT NULL,
dbGenre VARCHAR2(20),
dbUK_release_date DATE,
dbFilename VARCHAR2(50),
dbRuntime NUMBER(4),
dbClass CHAR(3),
CONSTRAINT vod_film_PK PRIMARY KEY (dbFIlmId),
CONSTRAINT vod_film_class_FK FOREIGN KEY (dbClass) REFERENCES
vod_classification (dbClassId) ON DELETE SET NULL
);
CREATE TABLE vod_role (
dbFilmId Char(4) NOT NULL,
dbActorId CHAR(4) NOT NULL,
dbCharacterName VARCHAR2(25) NOT NULL,
dbFirstAppearance NUMBER(6),
dbDescription CLOB,
CONSTRAINT vod_role_PK PRIMARY KEY (dbFilmId, dbActorId, dbCharacterName),
CONSTRAINT vod_role_film_FK FOREIGN KEY (dbFilmId) REFERENCES vod_film (dbFilmId)
ON DELETE CASCADE,
CONSTRAINT vod_role_actor_FK FOREIGN KEY (dbActorId) REFERENCES vod_actor (dbActorId)
ON DELETE CASCADE
);
//Insert into vod_actor & vod_classification works fine
Executing code below gives the error:
INSERT INTO vod_film VALUES ('1', 'Toy Story 3', 'Lee', 'Unkrich', 'Comedy', '19-JUL-2010', 'ToyStory3.mpg', '103', 'U');
INSERT INTO vod_film VALUES ('2', 'Lord of the Rings: Fellowship of the ring', 'Peter', 'Jackson', 'Fantasy', '19-DEC-2001', 'Fellowship.mpg', '178', '12');
INSERT INTO vod_film VALUES ('3', 'Lord of the Rings: Two Towers', 'Peter', 'Jackson', 'Fantasy', '18-DEC-2002', 'TwoTowers.mpg', '179', '12');
INSERT INTO vod_film VALUES ('4', 'Lord of the Rings: Return of the King', 'Peter', 'Jackson', 'Fantasy', '17-DEC-2003', 'KingReturns.mpg', '201', '12');
INSERT INTO vod_film VALUES ('5', 'Face/Off', 'John', 'Woo', 'Action', '7-NOV-1997', 'FaceOff.mpg', '138', '18');
INSERT INTO vod_film VALUES ('6', 'The Nutty Professor', 'Tom', 'Shadyac', 'Comedy', '4-OCT-1996', 'NuttyProf.mpg', '95', '12');
So in this case different character lengths for the PK FK fields I think is the issue.
CREATE TABLE vod_classification (
dbClassId CHAR(4) NOT NULL,
....
CREATE TABLE vod_film (
...
dbClass CHAR(3),
Given constraint
CONSTRAINT vod_film_class_FK FOREIGN KEY (dbClass) REFERENCES
vod_classification (dbClassId)
Appear to be the issue. char(3) <> char(4) make them both the same. likely the 3 to 4.
If I remember right char pads spaces to the end so 'U ' will never equal 'U ' U w/ 2 spaces for 3 characters vs U with 3 spaces for 4 characters. One of the reasons I prefer varchar no padding of spaces. Why was char chosen here?

MySQL 5.6 Foreign Key Error Message

I am getting this error when I try to run this bit of code in SQLFiddle. It is using MySQL 5.6.
Cannot add or update a child row: a foreign key constraint fails (db_9_f9acae.order_items, CONSTRAINT order_items_ibfk_1 FOREIGN KEY (Donut_Order_ID) REFERENCES custorder (Donut_Order_ID))
My code looks like this:
CREATE TABLE Customer (
Customer_ID INTEGER PRIMARY KEY AUTO_INCREMENT,
CustFirstName VARCHAR(50) NOT NULL,
CustLastName VARCHAR(50) NOT NULL,
Address VARCHAR(50) NOT NULL,
AptNum VARCHAR(50),
City VARCHAR(50) NOT NULL,
State VARCHAR(13) NOT NULL,
Zip VARCHAR(15) NOT NULL,
HomePhn VARCHAR(20),
MobPhn VARCHAR(20),
OthPhn VARCHAR(20)
);
CREATE TABLE Donut (
Donut_ID INTEGER PRIMARY KEY,
Donut_Name VARCHAR(255) NOT NULL,
Donut_Description VARCHAR(255) NOT NULL,
Donut_Price FLOAT NOT NULL
);
CREATE TABLE CustOrder (
Donut_Order_ID INTEGER PRIMARY KEY,
Date DATE NOT NULL,
Notes VARCHAR(255) NOT NULL,
Customer_ID INTEGER,
FOREIGN KEY (Customer_ID) REFERENCES Customer (Customer_ID)
);
CREATE TABLE Order_Items (
Donut_Order_ID INTEGER NOT NULL,
Donut_ID INTEGER NOT NULL,
Qty INTEGER NOT NULL,
PRIMARY KEY (Donut_Order_ID, Donut_ID),
FOREIGN KEY (Donut_Order_ID) REFERENCES CustOrder (Donut_Order_ID),
FOREIGN KEY (Donut_ID) REFERENCES Donut (Donut_ID)
);
CREATE VIEW CustInfo AS
SELECT CONCAT(CustFirstName,' ', CustLastName) AS CustFullName,
Customer_ID,
Address,
AptNum,
City,
State,
Zip,
HomePhn,
MobPhn,
OthPhn
FROM Customer;
CREATE INDEX DonutIndex ON Donut (Donut_Name);
INSERT INTO Customer VALUES
(1, "John", "Glenn", 1, NULL, "Kennedy Space Center", "FL", "32899", "(321) 867-5000", NULL, NULL),
(2, "Theodore", "Von Karman", "4800 Oak Dr", "Jet Propulsion Laboratory", "Pasadena", "CA", "91109", "(818) 354-4321", NULL, NULL),
(3, "Margaret", "Hamilton", "555 Technology Square", "Charles Stark Draper Laboratory", "Cambridge", "MA", "02139", "(617) 258-1000", "(123)456-7890", NULL);
INSERT INTO Donut
VALUES
(1, 'Plain' , 'Plain Donut' , 1.50),
(2, 'Glazed' , 'Glazed Donut' , 1.75),
(3, 'Cinnamon' , 'Cinnamon Donut' , 1.75),
(4, 'Chocolate' , 'Chocolate Donut' , 1.75),
(5, 'Sprinkle' , 'Sprinkle Donut' , 1.75),
(6, 'Gluten-Free' , 'Gluten-Free Donut' , 2.00);
INSERT INTO Order_Items VALUES
(2 , 4 , 3),
(3, 2, 1);
INSERT INTO CustOrder VALUES
('1', '11-24-2017', NULL, '1'),
('2', '11-25-2017', NULL, '2');
This is my first time working with anything SQL related and have tried referring to the MySQL docs, but don't know what I'm doing wrong. The error does not appear until after the bottom 2 INSERT INTO statements are added. Any help would be greatly appreciated.
You are getting this error because you are trying to insert data set in table whose references are missing in referenced table for example in Order_Items you are trying to link custorder table with Donut_Order_ID 2 and 3 but it is empty
So first fill your custorder and then link with your table
INSERT INTO CustOrder VALUES
('1', '11-24-2017', NULL, '1'),
('2', '11-25-2017', NULL, '2');
INSERT INTO Order_Items VALUES
(2 , 4 , 3),
(3, 2, 1);
Also i see there is no reference present in CustOrder for Donut_Order_ID = 3 but in Order_Items data you have trying to link with this missing reference which will again give you error
demo

Aggregate Query depending on several tables

I want to create a database with information of employees, their jobs, salaries and projects
I want to keep information of the cost of a project (real value of project and the days a employee invested)
For employee and project each Employee has one role on the Project through the PK constraint, and allows for the addition of a new role type ("Tertiary" perhaps) in the future.
CREATE TABLE Employee(
EmployeeID INTEGER NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Sex CHAR(1) NOT NULL,
Address VARCHAR(80) NOT NULL,
Security VARCHAR(15) NOT NULL,
DeptID INTEGER NOT NULL,
JobID INTEGER NOT NULL
);
CREATE TABLE Departments (
DeptID INTEGER NOT NULL PRIMARY KEY,
DeptName VARCHAR(30) NOT NULL
);
CREATE TABLE Jobs (
JobID INTEGER NOT NULL PRIMARY KEY,
JobName VARCHAR(30) NOT NULL,
JobSalary DOUBLE(15,3) NOT NULL default '0.000',
JobSalaryperDay DOUBLE(15,3) NOT NULL default '0.000',
DeptID INTEGER NOT NULL
);
CREATE TABLE Project(
ProjectID INTEGER NOT NULL PRIMARY KEY,
ProjectDesc VARCHAR(200) NOT NULL,
StartDate DATE NOT NULL,
EndDate DATE NOT NULL,
DaysOfWork INTEGER NOT NULL,
NoEmployees INTEGER NOT NULL,
EstimatedCost DOUBLE(15,3) NOT NULL default '0.000',
RealCost DOUBLE(15,3) NOT NULL default '0.000'
);
CREATE TABLE `Project-Employee`(
ProjectID INTEGER NOT NULL,
EmployeeID INTEGER NOT NULL,
Note VARCHAR(200),
DaysWork INTEGER NOT NULL,
CONSTRAINT fk_ProjectID FOREIGN KEY (ProjectID) REFERENCES Project(ProjectID),
CONSTRAINT fk_EmployeeID FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeID)
);
INSERT INTO `Departments` VALUES (1, 'Outsourcing');
INSERT INTO `Departments` VALUES (2, 'Technician');
INSERT INTO `Departments` VALUES (3, 'Administrative');
INSERT INTO `Jobs` VALUES (1, 'welder' ,500.550,16.7 ,2);
INSERT INTO `Jobs` VALUES (2, 'turner' ,500.100,16.67,2);
INSERT INTO `Jobs` VALUES (3, 'assistant' ,650.100,21.67,2);
INSERT INTO `Jobs` VALUES (4, 'supervisor',800.909,26.70,3);
INSERT INTO `Jobs` VALUES (5, 'manager' ,920.345,30.68,3);
INSERT INTO `Jobs` VALUES (6, 'counter' ,520.324,17.35,1);
INSERT INTO `Employee` VALUES (10, 'Joe', 'M', 'Anywhere', '927318344', 1, 3);
INSERT INTO `Employee` VALUES (20, 'Moe', 'M', 'Anywhere', '827318322', 2, 3);
INSERT INTO `Employee` VALUES (30, 'Jack', 'M', 'Anywhere', '927418343', 3, 4);
INSERT INTO `Employee` VALUES (40, 'Marge','F', 'Evererre', '127347645', 1, 6);
INSERT INTO `Employee` VALUES (50, 'Greg' ,'M', 'Portland', '134547633', 3, 5);
INSERT INTO `Project` VALUES (1, 'The very first', '2008-7-04' , '2008-7-24' , 20, 5, 3000.50, 2500.00);
INSERT INTO `Project` VALUES (2, 'Second one pro', '2008-8-01' , '2008-8-30' , 30, 5, 6000.40, 6100.40);
INSERT INTO `Project-Employee` VALUES (1, 10, 'Worked all days' , 20);
INSERT INTO `Project-Employee` VALUES (1, 20, 'Worked just in defs', 11);
INSERT INTO `Project-Employee` VALUES (1, 30, 'Worked just in defs', 17);
INSERT INTO `Project-Employee` VALUES (1, 40, 'Contability ' , 8);
INSERT INTO `Project-Employee` VALUES (1, 50, 'Managed the project', 8);
So to get the total amount of the cost of a project and have it for future Work quote I would just sum the working days of each job for each employee in an aggregate query.
What would be the query to sum all working days knowing the employees involved in a particular project to know the cost generated for their work, Is it possible to know this with this design?
So lets suppose I know that in project 1, 5 employees were involved, and I know by other table "jobs" the salary I would pay each one of them per day
I am doing some queries here with sqlfiddle
UPDATE
CREATE TABLE `Sexes` (
Sex char(1) primary key
);
INSERT INTO Sexes values ('M');
INSERT INTO Sexes values ('F');
CREATE TABLE `Employee`(
EmployeeID INTEGER NOT NULL PRIMARY KEY,
Name VARCHAR(130) NOT NULL,
Sex CHAR(1) NOT NULL,
Address VARCHAR(380) NOT NULL,
Security VARCHAR(15) NOT NULL,
FOREIGN KEY (Sex) references Sexes (Sex),
CONSTRAINT `uc_EmployeeInfo` UNIQUE (`EmployeeID`,`Name`,`Security`)
);
CREATE TABLE `Department` (
DeptID INTEGER NOT NULL PRIMARY KEY,
DeptName VARCHAR(30) NOT NULL,
CONSTRAINT `uc_DeptName` UNIQUE (`DeptID`,`DeptName`)
);
CREATE TABLE `Dept-Employee`(
EmployeeID INTEGER NOT NULL,
DeptID INTEGER NOT NULL,
CONSTRAINT fk_DeptID FOREIGN KEY (DeptID) REFERENCES `Department`(DeptID),
CONSTRAINT fk_EmployeeID FOREIGN KEY (EmployeeID) REFERENCES `Employee`(EmployeeID)
);
CREATE TABLE `Dept-Manager`(
EmployeeID INTEGER NOT NULL,
DeptID INTEGER NOT NULL,
CONSTRAINT fk_DeptIDs FOREIGN KEY (DeptID) REFERENCES `Department`(DeptID),
CONSTRAINT fk_EmployeeIDs FOREIGN KEY (EmployeeID) REFERENCES `Employee`(EmployeeID)
);
CREATE TABLE `Jobs` (
JobID INTEGER NOT NULL PRIMARY KEY,
JobName VARCHAR(30) NOT NULL,
JobSalary DECIMAL(7,3) NOT NULL default '0000.000',
JobSalaryperDay DECIMAL(7,3) NOT NULL default '0000.000',
CONSTRAINT `uc_jobs` UNIQUE (`JobID`,`JobName`)
);
CREATE TABLE `Jobs-Employee`(
EmployeeID INTEGER NOT NULL,
JobID INTEGER NOT NULL,
CONSTRAINT fk_JobIDs FOREIGN KEY (JobID) REFERENCES `Jobs`(JobID),
CONSTRAINT fk_EmployeeIDss FOREIGN KEY (EmployeeID) REFERENCES `Employee`(EmployeeID)
);
CREATE TABLE `Project`(
ProjectID INTEGER NOT NULL PRIMARY KEY,
ProjectName VARCHAR(200) NOT NULL,
StartDate DATE NOT NULL,
DaysOfWork INTEGER NOT NULL,
NoEmployees INTEGER NOT NULL,
EstimatedCost DECIMAL(9,3) NOT NULL default '000000.000',
RealCost DECIMAL(9,3) NOT NULL default '000000.000',
CONSTRAINT `uc_project` UNIQUE (`ProjectID`,`ProjectName`)
);
CREATE TABLE `Project-Employee`(
ProjectID INTEGER NOT NULL,
EmployeeID INTEGER NOT NULL,
Note VARCHAR(200),
DaysWork INTEGER NOT NULL,
CONSTRAINT fk_ProjectIDsss FOREIGN KEY (ProjectID) REFERENCES `Project`(ProjectID),
CONSTRAINT fk_EmployeeIDsss FOREIGN KEY (EmployeeID) REFERENCES `Employee`(EmployeeID)
);
INSERT INTO `Department` VALUES (1, 'Outsourcing');
INSERT INTO `Department` VALUES (2, 'Technician');
INSERT INTO `Department` VALUES (3, 'Administrative');
INSERT INTO `Jobs` VALUES (1, 'welder' ,500.550, 16.7 );
INSERT INTO `Jobs` VALUES (2, 'turner' ,500.100, 16.67);
INSERT INTO `Jobs` VALUES (3, 'assistant' ,650.100, 21.67);
INSERT INTO `Jobs` VALUES (4, 'supervisor',800.909, 26.70);
INSERT INTO `Jobs` VALUES (5, 'manager' ,920.345, 30.68);
INSERT INTO `Jobs` VALUES (6, 'counter' ,520.324, 17.35);
INSERT INTO `Employee` VALUES (10, 'Joe', 'M', 'Joewhere', '927318344');
INSERT INTO `Employee` VALUES (20, 'Moe', 'M', 'Moewhere', '827318322');
INSERT INTO `Employee` VALUES (30, 'Jack', 'M', 'Jaswhere', '927418343');
INSERT INTO `Employee` VALUES (40, 'Marge','F', 'Evererre', '127347645');
INSERT INTO `Employee` VALUES (50, 'Greg' ,'M', 'Portland', '134547633');
INSERT INTO `Dept-Employee` VALUES (10,1);
INSERT INTO `Dept-Employee` VALUES (20,2);
INSERT INTO `Dept-Employee` VALUES (30,3);
INSERT INTO `Dept-Employee` VALUES (40,1);
INSERT INTO `Dept-Employee` VALUES (50,3);
INSERT INTO `Jobs-Employee` VALUES (10,3);
INSERT INTO `Jobs-Employee` VALUES (20,3);
INSERT INTO `Jobs-Employee` VALUES (30,4);
INSERT INTO `Jobs-Employee` VALUES (40,6);
INSERT INTO `Jobs-Employee` VALUES (50,5);
INSERT INTO `Project` VALUES (1, 'The very first', '2008-7-04' , 20, 5, 3000.50, 2500.00);
INSERT INTO `Project` VALUES (2, 'Second one pro', '2008-8-01' , 30, 5, 6000.40, 6100.40);
INSERT INTO `Project-Employee` VALUES (1, 10, 'Worked all days' , 20);
INSERT INTO `Project-Employee` VALUES (1, 20, 'Worked just in defs', 11);
INSERT INTO `Project-Employee` VALUES (1, 30, 'Worked just in defs', 17);
INSERT INTO `Project-Employee` VALUES (1, 40, 'Contability ' , 8);
INSERT INTO `Project-Employee` VALUES (1, 50, 'Managed the project', 8);
To the new structure I did this
CREATE VIEW `Emp-Job` as
SELECT e.*,j.jobID
FROM Employee e,`Jobs-Employee` j
WHERE e.EmployeeID = j.EmployeeID;
CREATE VIEW `employee_pay` as
select e.*, j.jobname, j.jobsalary, j.jobsalaryperday
from `Emp-Job` e
inner join `Jobs` j
on e.JobID = j.JobID;
create view project_pay as
select pe.projectid, pe.employeeid, pe.dayswork,
e.jobsalaryperday, (e.jobsalaryperday * dayswork) as total_salary
from `Project-Employee` pe
inner join `employee_pay` e
on e.employeeid = pe.employeeid
The data at the end of your question doesn't seem to match the data in your INSERT statements.
Have you ever heard of "divide and conquer"? This is a good time to use it. Here's what I'd do.
create view employee_pay as
select e.*, j.jobname, j.jobsalary, j.jobsalaryperday
from employee e
inner join jobs j on e.jobid = j.jobid
create view project_pay as
select pe.projectid, pe.employeeid, pe.dayswork,
e.jobsalaryperday, (e.jobsalaryperday * dayswork) as total_salary
from project_employee pe
inner join employee_pay e
on e.employeeid = pe.employeeid
I'd do that, because I expect those views to be generally useful. (Especially for debugging.) Having created those views, the total for a project is dead simple.
select projectid, sum(total_salary) as total_salaries
from project_pay
group by projectid
projectid total_salaries
--
1 1509.91
You really don't want to use DOUBLE for money. Use DECIMAL instead.
Use this query to sort out why my sum doesn't match yours.
select p.*, e.name
from project_pay p
inner join employee e on e.employeeid = p.employeeid;
projectid employeeid dayswork jobsalaryperday total_salary name
1 10 20 21.67 433.4 Joe
1 20 11 21.67 238.37 Moe
1 30 17 26.7 453.9 Jack
1 40 8 17.35 138.8 Marge
1 50 8 30.68 245.44 Greg
Anti-patterns
Broken identity
Whenever you see a table like this one
CREATE TABLE Departments (
DeptID INTEGER NOT NULL PRIMARY KEY,
DeptName VARCHAR(30) NOT NULL
);
you should assume its structure is wrong, and dig deeper. (It's presumed guilty until proven innocent.) The anti-pattern you look for
integer as an artificial primary key, along with
no other unique constraints.
A table like this allows the real data to be duplicated, eliminating the usefulness of an artificial key.
DeptID DeptName
--
1 Wibble
2 Wibble
...
175 Wibble
A table like this will allow multiple foreign key references, too. That means some of the foreign keys might reference Wibble (DeptID = 1), some might reference Wibble (DeptID = 175), and so on.
To fix that, add a UNIQUE constraint on DeptName.
Missing foreign key references
Whenever you see a table like this one
CREATE TABLE Employee(
EmployeeID INTEGER NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
...
DeptID INTEGER NOT NULL,
JobID INTEGER NOT NULL
);
you should assume its structure is wrong, and dig deeper. (Again, it's presumed guilty until proven innocent.) The anti-pattern you look for
ID numbers from other tables, along with
no foreign key constraints referencing those tables.
To fix that, add foreign key constraints for DeptID and JobID. On MySQL, make sure you're using the INNODB engine, too. (As of MySQL 5.6, MyISAM still won't enforce foreign key constraints, but it won't give you an error or warning if you write them. They're parsed and ignored.)
If you come to MySQL from another dbms, you'll be surprised to find that MySQL doesn't support inline foreign key reference syntax. That means you can't write this.
DeptID integer not null references Departments (DeptID)
Instead, you have to write a separate foreign key clause in the CREATE TABLE statement. (Or use a separate ALTER TABLE statement to declare the FK reference.)
DeptID integer not null,
foreign key (DeptID) references Departments (DeptID)
Search this page for "inline ref", but read the whole thing.
Missing CHECK() constraints
MySQL doesn't enforce CHECK() constraints, so for columns that beg for a CHECK() constraint, you need a table and a foreign key reference. When you see a structure like this
CREATE TABLE Employee(
EmployeeID INTEGER NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Sex CHAR(1) NOT NULL,
the column "Sex" begs for a CHECK() constraint.
CREATE TABLE Employee(
EmployeeID INTEGER NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Sex CHAR(1) NOT NULL CHECK( Sex IN ('M', 'F')),
But MySQL doesn't enforce CHECK() constraints, so you need another table and a foreign key reference.
create table sexes (
sex char(1) primary key
);
insert into sexes values ('M');
insert into sexes values ('F');
CREATE TABLE Employee(
EmployeeID INTEGER NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Sex CHAR(1) NOT NULL,
...
foreign key (Sex) references Sexes (Sex)
I'd consider CHECK() constraints for most of these columns. Some can be implemented as tables with foreign key references.
Employee.Security
Jobs.JobSalary
Jobs.JobSalaryperDay
Project.DaysOfWork
Project.NoEmployees
Project.EstimatedCost
Project.RealCost
Project_Employee.DaysWork
Using floating-point data types for money
Don't do that. Floating-point numbers are useful approximations, but they're still approximations. Use DECIMAL instead.