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

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

Related

Sum of multiple rows in sql with join statement

I am trying to sum multiple rows of the same athlete so it will return the total amount of medals that they have won overall. I have the following code:
CREATE TABLE athlete (
athlete_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name TINYTEXT NOT NULL,
country TINYTEXT NOT NULL,
birthdate DATE NOT NULL,
age INT UNSIGNED,
height_inch INT UNSIGNED,
PRIMARY KEY (athlete_id)
);
INSERT INTO athlete (name, country, birthdate, age, height_inch) VALUES ('Simone Biles', 'United States', '1997-03-14', 24, 56);
INSERT INTO athlete (name, country, birthdate, age, height_inch) VALUES ('Michael Phelps', 'United States', '1985-06-30', 36, 76);
CREATE TABLE sport (
sport_id INT UNSIGNED NOT NULL,
sport TINYTEXT NOT NULL,
PRIMARY KEY (sport_id)
);
INSERT INTO sport VALUES (101, 'Skiing');
INSERT INTO sport VALUES (102, 'Biathlon');
INSERT INTO sport VALUES (103, 'Curling');
INSERT INTO sport VALUES (104, 'Skating');
INSERT INTO sport VALUES (105, 'Ice Hockey');
INSERT INTO sport VALUES (106, 'Luge');
INSERT INTO sport VALUES (107, 'Snowboard');
INSERT INTO sport VALUES (108, 'Basketball');
INSERT INTO sport VALUES (109, 'Gymnastics');
INSERT INTO sport VALUES (110, 'Swimming');
INSERT INTO sport VALUES (111, 'Diving');
INSERT INTO sport VALUES (112, 'Track and Field');
INSERT INTO sport VALUES (113, 'Badminton');
INSERT INTO sport VALUES (114, 'Tennis');
INSERT INTO sport VALUES (115, 'Volleyball');
INSERT INTO sport VALUES (116, 'Skateboard');
INSERT INTO sport VALUES (117, 'Soccer');
INSERT INTO sport VALUES (118, 'Golf');
INSERT INTO sport VALUES (119, 'Cycling');
INSERT INTO sport VALUES (120, 'Climbing');
INSERT INTO sport VALUES (121, 'Surfing');
INSERT INTO sport VALUES (122, 'Water Polo');
INSERT INTO sport VALUES (123, 'Karate');
CREATE TABLE olympics (
olympics_id INT UNSIGNED NOT NULL,
season TINYTEXT NOT NULL,
year YEAR NOT NULL,
city TINYTEXT NOT NULL,
PRIMARY KEY (olympics_id)
);
INSERT INTO olympics VALUES (1001, 'Summer', 1936, 'Berlin');
INSERT INTO olympics VALUES (1002, 'Summer', 1956, 'Melbourne');
INSERT INTO olympics VALUES (1003, 'Summer', 1960, 'Rome');
INSERT INTO olympics VALUES (1004, 'Summer', 1964, 'Tokyo');
INSERT INTO olympics VALUES (1005, 'Summer', 1976, 'Montreal');
INSERT INTO olympics VALUES (1006, 'Summer', 1984, 'Los Angelos');
INSERT INTO olympics VALUES (1007, 'Summer', 1996, 'Atlanta');
INSERT INTO olympics VALUES (1008, 'Summer', 2000, 'Sydney');
INSERT INTO olympics VALUES (1009, 'Summer', 2004, 'Athens');
INSERT INTO olympics VALUES (1010, 'Summer', 2008, 'Beijing');
INSERT INTO olympics VALUES (1011, 'Summer', 2012, 'London');
INSERT INTO olympics VALUES (1012, 'Summer', 2016, 'Rio de Janeiro');
INSERT INTO olympics VALUES (1013, 'Summer', 2020, 'Tokyo');
CREATE TABLE sport_events (
sport_id INT UNSIGNED NOT NULL,
event_id INT UNSIGNED NOT NULL,
event TINYTEXT NOT NULL,
PRIMARY KEY (event_id),
FOREIGN KEY (sport_id) REFERENCES sport (sport_id)
);
INSERT INTO sport_events VALUES (101, 501, 'Alpine Skiing');
INSERT INTO sport_events VALUES (101, 502, 'Cross-Country Skiing');
INSERT INTO sport_events VALUES (104, 503, 'Figure Skating');
INSERT INTO sport_events VALUES (101, 504, 'Freestyle Skiing');
INSERT INTO sport_events VALUES (104, 505, 'Short Track Speed Skating');
INSERT INTO sport_events VALUES (101, 506, 'Ski Jumping');
INSERT INTO sport_events VALUES (107, 507, 'Half-pipe');
INSERT INTO sport_events VALUES (101, 508, 'Half-pipe');
INSERT INTO sport_events VALUES (104, 509, 'Speed Skating');
INSERT INTO sport_events VALUES (109, 510, 'Artistic Gymnastics');
INSERT INTO sport_events VALUES (109, 511, 'Rhythmic Gymnastics');
INSERT INTO sport_events VALUES (115, 512, 'Beach Volleyball');
INSERT INTO sport_events VALUES (112, 513, 'High Jump');
INSERT INTO sport_events VALUES (112, 514, '100m');
INSERT INTO sport_events VALUES (112, 515, '200m');
INSERT INTO sport_events VALUES (112, 516, '400m');
INSERT INTO sport_events VALUES (112, 517, '800m');
INSERT INTO sport_events VALUES (112, 518, '4x100m relay');
INSERT INTO sport_events VALUES (112, 519, 'Triple Jump');
CREATE TABLE athlete_sport (
athlete_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
sport_id INT UNSIGNED NOT NULL,
PRIMARY KEY (athlete_id),
FOREIGN KEY (athlete_id) REFERENCES athlete (athlete_id),
FOREIGN KEY (sport_id) REFERENCES sport (sport_id)
);
INSERT INTO athlete_sport (sport_id) VALUES (109);
INSERT INTO athlete_sport (sport_id) VALUES (110);
CREATE TABLE compete (
athlete_id INT UNSIGNED NOT NULL,
olympics_id INT UNSIGNED NOT NULL,
sport_id INT UNSIGNED NOT NULL,
event_id INT UNSIGNED,
gold INT UNSIGNED,
silver INT UNSIGNED,
bronze INT UNSIGNED,
FOREIGN KEY (olympics_id) REFERENCES olympics (olympics_id),
FOREIGN KEY (athlete_id) REFERENCES athlete (athlete_id),
FOREIGN KEY (event_id) REFERENCES sport_events (event_id)
);
INSERT INTO compete VALUES (1, 1012, 109, 510, 4, 0, 1);
INSERT INTO compete VALUES (1, 1013, 109, 510, 0, 1, 1);
INSERT INTO compete VALUES (2, 1009, 110, NULL, 6, 0, 2);
INSERT INTO compete VALUES (2, 1010, 110, NULL, 8, 0, 0);
INSERT INTO compete VALUES (2, 1011, 110, NULL, 4, 2, 0);
INSERT INTO compete VALUES (2, 1012, 110, NULL, 5, 1, 0);
I have looked at other answers people have posted and most of them are just saying to use group by, but when I use that it just orders the either names or number of medals together just in a different order. I'm trying to get it so it says that the total number of medals simone biles has is 7 and michael phelps is 28 just in a single table.
This is the query I have that returns the sum of the medals for each olympic games they've been in, but again if I use group by it just orders them.
select a.name, gold+silver+bronze as medalTotal from athlete a join compete c using (athlete_id) group by medalTotal;
+----------------+------------+
| name | medalTotal |
+----------------+------------+
| Simone Biles | 2 |
| Simone Biles | 5 |
| Michael Phelps | 6 |
| Michael Phelps | 8 |
+----------------+------------+
you need to do the following:
group by athlete
sum each medal type
add the sum of each medal type
You need to group by athlete, not total.
You have to use an aggregation function to combine values from all the rows in a group. Use SUM() to add them together.
select a.name, SUM(b.gold+b.silver+b.bronze) as medalTotal
from athlete a
join compete c using (athlete_id)
group by a.athlete_id;
You should apply group by using something unique like athelet id.
This get all atheletes with all medals number including with zero medals
if you want just athelet with medals only use join only.
select
a.name, sum(gold+silver+bronze) as medalTotal
from
athlete a
left join
compete c on c.athlete_id = a.athlete_id
group by
a.athlete_id

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

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

Many-to-Many Tables SQL

I have to do a many to many tables between a table MEAL and a table RESTAURANT. First I created the two tables:
CREATE TABLE RESTAURANT (
ID_Restaurant VARCHAR(10) NOT NULL,
ID_Hotel VARCHAR(10) NOT NULL,
Name VARCHAR(30) NOT NULL,
Number_of_Tables INT(3) NOT NULL,
PRIMARY KEY (ID_Restaurant),
FOREIGN KEY (ID_Hotel) REFERENCES HOTEL (ID_Hotel));
CREATE TABLE MEAL(
ID_Meal VARCHAR(10) NOT NULL,
Name VARCHAR(30) NOT NULL,
Preparation_Time VARCHAR(20),
Cooking_Time VARCHAR(20),
PRIMARY KEY (ID_Meal));
Then I created the 'joint' tables:
CREATE TABLE MEAL_SERVED(
ID_Meal VARCHAR(10) NOT NULL,
ID_Restaurant VARCHAR(10) NOT NULL,
Price INT(5) NOT NULL,
PRIMARY KEY (ID_Meal, ID_Restaurant, Price),
FOREIGN KEY(ID_Meal) REFERENCES MEAL(ID_Meal),
FOREIGN KEY(ID_Restaurant) REFERENCES RESTAURANT (ID_Restaurant));
I entered some data in the first two tables:
INSERT INTO RESTAURANT(ID_Restaurant, ID_Hotel, Name, Number_of_Tables)
VALUES ('REST1', 'H1', 'Benares Indisk Restaurant', 26);
('REST2', 'H2', 'La Gaichel', 35),
('REST3', 'H3', 'Tapas Restaurant', 17),
('REST4', 'H4', 'Faubourg 101', 19),
('REST5', 'H5', 'Pizzeria Roma', 38);
INSERT INTO MEAL(ID_Meal, Name, Preparation_Time, Cooking_Time)
VALUES ('MEAL1', 'Croque-Monsieur', '5 min', '4 min'),
('MEAL2', 'Salad', '6 min', NULL),
('MEAL3', 'Hot Dog', '3 min', '2min'),
('MEAL4', 'Panini', '6 min', '5 min'),
('MEAL5', 'Coca-Cola', NULL, NULL);
Until, now there is no problem, but when I tried to enter data in the third tables with:
INSERT INTO MEAL_SERVED(ID_Meal, ID_Restaurant, Price)
VALUES ('MEAL1', 'REST1', 50),
('MEAL4', 'REST1', 50),
('MEAL5', 'REST1', 35),
('MEAL1', 'REST2', 3.5),
('MEAL2', 'REST2', 3.5),
('MEAL4', 'REST2', 5);
for instance, then I have an error message:
FOREIGN KEY constraint failed: INSERT INTO MEAL_SERVED(ID_Meal, ID_Restaurant, Price)
I don't understand why I have this message and how to correct it. Thanks in advance.
As Shadow said in the comment section.
First, fix your typo in one of your SQL statements:
INSERT INTO RESTAURANT(ID_Restaurant, ID_Hotel, Name, Number_of_Tables)
VALUES ('REST1', 'H1', 'Benares Indisk Restaurant', 26);
('REST2', 'H2', 'La Gaichel', 35),
('REST3', 'H3', 'Tapas Restaurant', 17),
('REST4', 'H4', 'Faubourg 101', 19),
('REST5', 'H5', 'Pizzeria Roma', 38);
should be:
INSERT INTO RESTAURANT(ID_Restaurant, ID_Hotel, Name, Number_of_Tables)
VALUES ('REST1', 'H1', 'Benares Indisk Restaurant', 26),
('REST2', 'H2', 'La Gaichel', 35),
('REST3', 'H3', 'Tapas Restaurant', 17),
('REST4', 'H4', 'Faubourg 101', 19),
('REST5', 'H5', 'Pizzeria Roma', 38);
Second:
Do yourself a favor and use integers for primary keys and with the auto_increment option, you can just ignore the id.
CREATE TABLE RESTAURANT (
`id` INT NOT NULL AUTO_INCREMENT,
`hotel` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
`numberOfTables` INT NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (hotel) REFERENCES HOTEL (`id`));
CREATE TABLE MEAL(
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(30) NOT NULL,
`preparationTime` VARCHAR(20),
`cookingTime` VARCHAR(20),
PRIMARY KEY (`id`));
CREATE TABLE MEAL_SERVED(
`id` INT NOT NULL AUTO_INCREMENT,
`meal` INT NOT NULL,
`restaurant` INT NOT NULL,
Price FLOAT NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY(meal) REFERENCES MEAL(`id`),
FOREIGN KEY(restaurant) REFERENCES RESTAURANT (`id`));
Data:
INSERT INTO RESTAURANT(`hotel`, `name`, `numberOfTables`)
VALUES ('1', 'Benares Indisk Restaurant', 26),
(2, 'La Gaichel', 35),
(3, 'Tapas Restaurant', 17),
(4, 'Faubourg 101', 19),
(5, 'Pizzeria Roma', 38);
INSERT INTO MEAL(`name`, `preparationTime`, `cookingTime`)
VALUES ('Croque-Monsieur', '5 min', '4 min'),
('Salad', '6 min', NULL),
('Hot Dog', '3 min', '2min'),
('Panini', '6 min', '5 min'),
('Coca-Cola', NULL, NULL);
INSERT INTO MEAL_SERVED(`meal`, `restaurant`, `price`)
VALUES (1, 1, 50),
(4, 1, 50),
(5, 1, 35),
(1, 2, 3.5),
(2, 2, 3.5),
(4, 2, 5);
Third:
INT(3) has no effects. The space for the INT will be allocated anyway.
You can use TINYINT or SMALLINT instad, maybe. Look here: https://dev.mysql.com/doc/refman/5.7/en/integer-types.html
Fourth:
Use camel-case or snake-case but not both please ;-)

SQL Code not running: Drop Tables and Organization issue maybe?

So, this is my code. When I attempt to compile it in the school provided engine, I've gotten a couple errors, and they do change each time I run it, but the one I currently have is this:
ERROR 1064 (42000) at line 123: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the
right syntax to use near '9:30, 'L210', 103, 15), (86, 25, 2,
6/10/2007 9:30, 'L210', 107, 15), (89, 25, 5' at line 2
I've already tried to take out the spaces, but it makes no difference. Would this have anything to do with the order in which I take information? Or is it something else?
I'm also not sure that the tables are dropping at step one.
/*Step One: Drop Tables*/
DROP TABLE IF EXISTS Student;
DROP TABLE IF EXISTS Zipcode;
DROP TABLE IF EXISTS Instructor;
DROP TABLE IF EXISTS Enrollment;
DROP TABLE IF EXISTS Sections;
DROP TABLE IF EXISTS Course;
/*Step Two: Create Tables*/
CREATE TABLE Zipcode
(
zip int(11),
city varchar(25) NOT NULL,
state varchar(2) NOT NULL,
PRIMARY KEY (zip)
);
CREATE TABLE Student
(
student_ID int(6) UNIQUE,
salutation varchar(5),
first_name varchar(25) NOT NULL,
last_name varchar(25) NOT NULL,
street_address varchar(50),
phone int(15) NOT NULL,
employer varchar(50) ,
registration_date date NOT NULL,
zip int(11),
PRIMARY KEY (student_ID),
FOREIGN KEY (zip) REFERENCES Zipcode (zip)
);
CREATE TABLE Course
(
course_ID int(6) UNIQUE,
description varchar(50) NOT NULL,
cost dec(8,2) NOT NULL,
prerequisite int(6),
PRIMARY KEY (course_ID),
FOREIGN KEY (prerequisite) REFERENCES Course (course_ID)
);
CREATE TABLE Instructor
(
Instructor_ID int(6) UNIQUE,
salutation varchar(5),
first_name varchar(25) NOT NULL,
last_name varchar(25) NOT NULL,
street_address varchar(50),
zip int(11) NOT NULL,
PRIMARY KEY (Instructor_ID),
FOREIGN KEY (zip) REFERENCES zipcode (zip)
);
CREATE TABLE Sections
(
section_ID int(8) UNIQUE,
course_id int(6) NOT NULL,
course_section_num int(6) NOT NULL,
start_date_time datetime NOT NULL,
location varchar(10),
instructor_ID int(6) NOT NULL,
capacity int(3),
PRIMARY KEY (section_ID),
FOREIGN KEY (instructor_ID) REFERENCES Instructor (instructor_ID),
FOREIGN KEY (course_ID) REFERENCES Course (course_ID)
);
CREATE TABLE Enrollment
(
student_ID int(6) UNIQUE,
section_ID int(8) UNIQUE,
enroll_date datetime NOT NULL,
final_grade char(1),
PRIMARY KEY (section_ID, student_ID),
FOREIGN KEY (section_ID) REFERENCES sections (section_ID),
FOREIGN KEY (student_ID) REFERENCES student (student_ID)
);
/*Step Three: Insert Rows*/
INSERT INTO Zipcode VALUES
(7024, 'Ft. Lee', 'NJ'),
(7047, 'North Bergen', 'NJ'),
(10005, 'New York', 'NY'),
(10015, 'New York', 'NY'),
(10025, 'New York', 'NY'),
(10035, 'New York', 'NY'),
(11419, 'Richmond Hill', 'NY'),
(11435, 'Jamaica', 'NY');
INSERT INTO Student VALUES
(102, 'Mr.', 'Fred', 'Crocitto', '101-09 120th St.', 718-555-5555, 'Albert Hildegard Co.', 1/22/2007, 11419),
(103, 'Ms.', 'J.', 'Landry', '7435 Boulevard East #45', 201-555-5555, 'Albert Hildegard Co.', 1/22/2007, 7047),
(104, 'Ms.', 'Laetia', 'Enison', '144-61 87th Ave', 718-555-5555, 'Albert Hildegard Co.', 1/22/2007, 11435),
(105, 'Mr.', 'Angel', 'Moskowitz', '320 John St.', 201-555-5555, 'Alex. & Alexander', 1/22/2007, 7024),
(163, 'Ms.', 'Nicole', 'Gillen', '4301 N Ocean #103', 904-555-5555, 'Oil of America Corp.', 2/2/2007, 10025),
(223, 'Mr.', 'Frank', 'Pace', '13 Burlington Dr.', 203-555-5555, 'Board Utilities', 2/8/2007, 10025),
(399, 'Mr.', 'Jerry', 'Abdou', '460 15th St. #4', 718-555-5555, 'Health Mgmt.Systems', 2/23/2007, 10025);
INSERT INTO Course VALUES
(330, 'Network Administration', 1195, 130),
(310, 'Operating Systems', 1195, NULL),
(142, 'Project Management', 1195, 20),
(140, 'Systems Analysis', 1195, 20),
(130, 'Intro to Unix', 1195, 310),
(25, 'Intro to Programming', 1195, 140),
(20, 'Intro to Information Systems', 1195, NULL);
INSERT INTO Instructor VALUES
(101, 'Mr.', 'Fernand', 'Hanks', '100 East 87th', 10015),
(102, 'Mr.', 'Tom', 'Wojick', '518 West 120th', 10025),
(103, 'Ms.', 'Nina', 'Schorin', '210 West 101st', 10025),
(104, 'Mr.', 'Gary', 'Pertez', '34 Sixth Ave', 10035),
(105, 'Ms.', 'Anita', 'Morris', '34 Maiden Lane', 10015),
(106, 'Rev.', 'Todd', 'Smythe', '210 West 101st', 10025),
(107, 'Dr.', 'Marilyn', 'Frantzen', '254 Bleeker', 10005);
INSERT INTO Sections VALUES
(81, 20, 2, 7/24/2007 9:30, 'L210', 103, 15),
(86, 25, 2, 6/10/2007 9:30, 'L210', 107, 15),
(89, 25, 5, 5/15/2007 9:30, 'L509', 103, 25),
(92, 25, 8, 6/13/2007 9:30, 'L509', 106, 25),
(104, 330, 1, 7/14/2007 10:30, 'L511', 104, 25),
(119, 142, 1, 7/14/2007 9:30, 'L211', 103, 25),
(155, 122, 4, 5/4/2007 9:30, 'L210', 107, 15);
INSERT INTO Enrollment VALUES
(102, 86, 1/30/2007, NULL, 'B'),
(102, 89, 1/30/2007, 92,'A'),
(103, 81, 1/30/2007, NULL),
(104, 81, 1/30/2007, NULL, 'A'),
(163, 92, 2/10/2007, NULL),
(223, 104, 2/16/2007, NULL,'C'),
(223, 119, 2/16/2007, NULL);
/*Step Four: Select Statements*/
SELECT * FROM Student;
SELECT * FROM Zipcode;
SELECT * FROM Instructor;
SELECT * FROM Course;
SELECT * FROM Sections;
SELECT * FROM Enrollment;
The issue identified by the error message is the datetime literal, here:
INSERT INTO Sections VALUES
(81, 20, 2, 7/24/2007 9:30, 'L210', 103, 15)
^^^^^^^^^^^^^^
To get a value assigned to a datetime column, you could do this:
(81, 20, 2, '2007-07-24 09:30', 'L210', 103, 15)
^^^^^^^^^^^^^^^^^^
Datetime literals should be enclosed in single quotes, and represented in a format like 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MI:SS'.
(It is also possible to pass numeric decimal values in. But no one really does that. Just use a string literal in the correct format. I believe newer versions of MySQL are more lenient than earlier versions, regarding the strictness of two characters for month, and two characters for day, and using a delimiter other than the dash. I think its also possible to omit the delimiter for a datetime
I think MySQL would also accept something like this:
'20070724093000'
But again, no one really does that. Just supply the values as strings in the standard 'YYYY-MM-DD HH:MI:SS' format.

Error 1136 in mysql

i keep getting the error 1136 in mysql, i need help, what's wrong with this code?
CREATE table Artist (
ArtistID INT,Salary varchar (20),Contract_End_Date date,Trackname varchar (20),
Artistname varchar (15),
Fname varchar (20),
Lname varchar (20),
Birthday date ,
PRIMARY KEY(ArtistID),
FOREIGN KEY (Salary) REFERENCES Contract(Salary),
FOREIGN KEY (Contract_End_Date) REFERENCES Contract(Contract_End_Date),
FOREIGN KEY (Trackname) REFERENCES Track(Trackname));
INSERT INTO Artist(ArtistID, Artistname, Fname, Lname, Birthday, Salary, Contract_End_Date, Trackname) VALUES (
'1','JM','John','Mcfierceson','1978-05-20','$100000','2017-05-08','Cries by the Ocean',
'2','Ray','Ray','Grueson','1990-07-10','$500000','2017-09-12','Jumping Jacks',
'3','Shiin','Charlie','Shiin','1989-02-12','$700000','2020-12-17','I can feel my head',
'4','King','Bobby','Naval','1978-09-24','$7878787','2014-10-11','Rain',
'5','Yellowman','Chris, Yellow','1984-11-11','$8000000','2014-09-08','Falling',
'6','Sting','Karl','Shakur','1967-10-06','$5600000','2014-05-15','X',
'7','Kboy','Kendrick','Maine','1990-12-25','$8099999','2021-09-12','Trick');
CREATE table Contract (
Contractcode varchar (20), Artistname varchar(15),
Contract_start_Date date,
Contract_End_Date date,
Salary varchar(20),
PRIMARY KEY(Contractcode),
FOREIGN KEY (Artistname) REFERENCES Artist(Artistname));
INSERT INTO Contract VALUES (
'1004JM', 'JM', '2011-05-08', '2017-05-08', '$100000 ',
'2424RG', 'Ray', '2013-09-12', '2017-09-12', '$500000',
'3446SC', 'Shiin', '2010-12-17', '2020-12-17', '$700000',
'9999BN', 'King', '1990-10-11', '2014-10-11', '$7878787',
'2546CY', 'Yellowman', '2000-09-08', '2014-09-08', '$8000000',
'4446KS', 'Sting', '1980-05-15', '2014-05-15', '$5600000',
'5454KM', 'Kboy', '2010-09-12', '2021-09-12', '$8099999');
CREATE table Track (
Trackname varchar (20),
Artistname varchar (15),
Tracktype varchar (20),
Tracklength int ,
PRIMARY KEY(Trackname),
FOREIGN KEY (Artistname) REFERENCES Artist(Artistname));
INSERT INTO Track VALUES (
'Cries by the Ocean', 'Jumping Jacks', 'I can feel my head', 'Rain', 'Falling', 'X', 'Trick',
'JM', 'Ray', 'Shiin', 'King', 'Yellowman', 'Sting', 'Kboy',
'Rock', 'Rock', 'Indie', 'RnB', 'Rock', 'Rock', 'Rock',
'4', '5', '3', '3', '5', '5', '5');
Mysql Error 1136 means Column count doesn't match value count.
You seem to be inserting multiple rows with a single insert statement.
Each row of data should be in its own set of parenthesis. And each set of parenthesis should be separated by a comma. Something like this:
INSERT INTO artist
(artistid, artistname, fname, lname, birthday, salary, contract_end_date, trackname)
VALUES
('1', 'JM', 'John', 'Mcfierceson', '1978-05-20', '$100000', '2017-05-08', 'Cries by the Ocean'),
('2', 'Ray', 'Ray', 'Grueson', '1990-07-10', '$500000', '2017-09-12', 'Jumping Jacks'),
('3', 'Shiin', 'Charlie', 'Shiin', '1989-02-12', '$700000', '2020-12-17', 'I can feel my head'),
('4', 'King', 'Bobby', 'Naval', '1978-09-24', '$7878787', '2014-10-11', 'Rain'),
('5', 'Yellowman', 'Chris, Yellow', '1984-11-11', '$8000000', '2014-09-08', 'Falling'),
('6', 'Sting', 'Karl', 'Shakur', '1967-10-06', '$5600000', '2014-05-15', 'X'),
('7', 'Kboy', 'Kendrick', 'Maine', '1990-12-25', '$8099999', '2021-09-12', 'Trick');
INSERT Syntax (Documentation)
You are trying to plug more data than you have fields for. Try this:
CREATE table Track ( Trackname varchar (20),
Artistname varchar (15),
Tracktype varchar (20),
Tracklength int ,
PRIMARY KEY(Trackname),
FOREIGN KEY (Artistname)
REFERENCES Artist(Artistname));
INSERT INTO Track VALUES ( 'Cries by the Ocean', 'JM', 'Rock', '4'),
('Jumping Jacks', 'Ray', 'Rock', '5');
Enclose each row in a set of (), one row of data at a time.