Using the Northwind Dataset, What query would generate the total orders under each employee? [closed] - mysql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
This post was edited and submitted for review 2 days ago.
Improve this question
The expected answer
would yield the following:
name
employee ID
subordinates
totalOrders
Dr. Andrew Fuller
2
1, 3, 5, 7, 6, 9, 8, 4
830
Mr. Steven Buchanan
5
7, 6, 9
224
Mrs. Margaret Peacock
4
156
Ms. Janet Leverling
3
127
Ms. Nancy Davolio
1
123
Ms. Laura Callahan
8
104
Mr. Robert King
7
72
Mr. Michael Suyama
6
67
Ms. Anne Dodsworth
9
43
Question Clarifications
The tally of the orders "under each employee" includes the orders fulfilled by the given employee, the orders for those that report to that employee, the order for those that report to those employees, etc, etc.
Notes:
The query to generate the number of orders for each employee is somewhat straight-forward
SELECT
CONCAT(TitleOfCourtesy, ' ', FirstName, ' ', LastName) AS name,
COUNT(Orders.OrderID) AS orders
FROM northwind.orders AS Orders
LEFT JOIN northwind.employees AS Employees
ON Orders.EmployeeID = Employees.EmployeeID
GROUP BY name
ORDER BY orders DESC
which gives
name
orders
Mrs. Margaret Peacock
156
Ms. Janet Leverling
127
Ms. Nancy Davolio
123
Ms. Laura Callahan
104
Dr. Andrew Fuller
96
Mr. Robert King
72
Mr. Michael Suyama
67
Ms. Anne Dodsworth
43
Mr. Steven Buchanan
42
But I don't know the right way to get from here to the final answer. I'd be grateful for any help you're able to provide.
Appendix:
For convenience I've hosted the Northwind dataset accessible with a MySQL client (ie. MySQL Workbench) at:
Hostname: northwind.techiteasy.ca
port: 3310
Username: mariadb
Password: password
However in order to keep the question self-contained, here some relevant snippets from the Northwind dataset:
-- ------------------------------------------
-- Table structure for `Employees`
-- ------------------------------------------
CREATE TABLE `Employees` (
`EmployeeID` INTEGER NOT NULL AUTO_INCREMENT,
`LastName` VARCHAR(20) NOT NULL,
`FirstName` VARCHAR(10) NOT NULL,
`Title` VARCHAR(30),
`TitleOfCourtesy` VARCHAR(25),
`BirthDate` DATETIME,
`HireDate` DATETIME,
`Address` VARCHAR(60),
`City` VARCHAR(15),
`Region` VARCHAR(15),
`PostalCode` VARCHAR(10),
`Country` VARCHAR(15),
`HomePhone` VARCHAR(24),
`Extension` VARCHAR(4),
`Photo` LONGBLOB,
`Notes` MEDIUMTEXT NOT NULL,
`ReportsTo` INTEGER,
`PhotoPath` VARCHAR(255),
`Salary` FLOAT,
CONSTRAINT `PK_Employees` PRIMARY KEY (`EmployeeID`)
);
CREATE INDEX `LastName` ON `Employees` (`LastName`);
CREATE INDEX `PostalCode` ON `Employees` (`PostalCode`);
-- ------------------------------------------
-- Records of Employees
-- ------------------------------------------
INSERT INTO Employees VALUES
(1, 'Davolio', 'Nancy', 'Sales Representative', 'Ms.', '1948-12-08 00:00:00', '1992-05-01 00:00:00', '507 - 20th Ave. E.\r\nApt. 2A', 'Seattle', 'WA', '98122', 'USA', '(206) 555-9857', '5467', NULL, 'Education includes a BA in psychology from Colorado State University in 1970. She also completed \"The Art of the Cold Call.\" Nancy is a member of Toastmasters International.', 2, 'http://accweb/emmployees/davolio.bmp', 2954.55),
(2, 'Fuller', 'Andrew', 'Vice President, Sales', 'Dr.', '1952-02-19 00:00:00', '1992-08-14 00:00:00', '908 W. Capital Way', 'Tacoma', 'WA', '98401', 'USA', '(206) 555-9482', '3457', NULL, 'Andrew received his BTS commercial in 1974 and a Ph.D. in international marketing from the University of Dallas in 1981. He is fluent in French and Italian and reads German. He joined the company as a sales representative, was promoted to sales manager in January 1992 and to vice president of sales in March 1993. Andrew is a member of the Sales Management Roundtable, the Seattle Chamber of Commerce, and the Pacific Rim Importers Association.', NULL, 'http://accweb/emmployees/fuller.bmp', 2254.49),
(3, 'Leverling', 'Janet', 'Sales Representative', 'Ms.', '1963-08-30 00:00:00', '1992-04-01 00:00:00', '722 Moss Bay Blvd.', 'Kirkland', 'WA', '98033', 'USA', '(206) 555-3412', '3355', NULL, 'Janet has a BS degree in chemistry from Boston College (1984). She has also completed a certificate program in food retailing management. Janet was hired as a sales associate in 1991 and promoted to sales representative in February 1992.', 2, 'http://accweb/emmployees/leverling.bmp', 3119.15),
(4, 'Peacock', 'Margaret', 'Sales Representative', 'Mrs.', '1937-09-19 00:00:00', '1993-05-03 00:00:00', '4110 Old Redmond Rd.', 'Redmond', 'WA', '98052', 'USA', '(206) 555-8122', '5176', NULL, 'Margaret holds a BA in English literature from Concordia College (1958) and an MA from the American Institute of Culinary Arts (1966). She was assigned to the London office temporarily from July through November 1992.', 2, 'http://accweb/emmployees/peacock.bmp', 1861.08),
(5, 'Buchanan', 'Steven', 'Sales Manager', 'Mr.', '1955-03-04 00:00:00', '1993-10-17 00:00:00', '14 Garrett Hill', 'London', null, 'SW1 8JR', 'UK', '(71) 555-4848', '3453', NULL, 'Steven Buchanan graduated from St. Andrews University, Scotland, with a BSC degree in 1976. Upon joining the company as a sales representative in 1992, he spent 6 months in an orientation program at the Seattle office and then returned to his permanent post in London. He was promoted to sales manager in March 1993. Mr. Buchanan has completed the courses \"Successful Telemarketing\" and \"International Sales Management.\" He is fluent in French.', 2, 'http://accweb/emmployees/buchanan.bmp', 1744.21),
(6, 'Suyama', 'Michael', 'Sales Representative', 'Mr.', '1963-07-02 00:00:00', '1993-10-17 00:00:00', 'Coventry House\r\nMiner Rd.', 'London', null, 'EC2 7JR', 'UK', '(71) 555-7773', '428', NULL, 'Michael is a graduate of Sussex University (MA, economics, 1983) and the University of California at Los Angeles (MBA, marketing, 1986). He has also taken the courses \"Multi-Cultural Selling\" and \"Time Management for the Sales Professional.\" He is fluent in Japanese and can read and write French, Portuguese, and Spanish.', 5, 'http://accweb/emmployees/davolio.bmp', 2004.07),
(7, 'King', 'Robert', 'Sales Representative', 'Mr.', '1960-05-29 00:00:00', '1994-01-02 00:00:00', 'Edgeham Hollow\r\nWinchester Way', 'London', null, 'RG1 9SP', 'UK', '(71) 555-5598', '465', NULL, 'Robert King served in the Peace Corps and traveled extensively before completing his degree in English at the University of Michigan in 1992, the year he joined the company. After completing a course entitled \"Selling in Europe,\" he was transferred to the London office in March 1993.', 5, 'http://accweb/emmployees/davolio.bmp', 1991.55),
(8, 'Callahan', 'Laura', 'Inside Sales Coordinator', 'Ms.', '1958-01-09 00:00:00', '1994-03-05 00:00:00', '4726 - 11th Ave. N.E.', 'Seattle', 'WA', '98105', 'USA', '(206) 555-1189', '2344', NULL, 'Laura received a BA in psychology from the University of Washington. She has also completed a course in business French. She reads and writes French.', 2, 'http://accweb/emmployees/davolio.bmp', 2100.50),
(9, 'Dodsworth', 'Anne', 'Sales Representative', 'Ms.', '1966-01-27 00:00:00', '1994-11-15 00:00:00', '7 Houndstooth Rd.', 'London', null, 'WG2 7LT', 'UK', '(71) 555-4444', '452', NULL, 'Anne has a BA degree in English from St. Lawrence College. She is fluent in French and German.', 5, 'http://accweb/emmployees/davolio.bmp', 2333.33);
-- ------------------------------------------
-- Table structure for `Orders`
-- ------------------------------------------
CREATE TABLE `Orders` (
`OrderID` INTEGER NOT NULL AUTO_INCREMENT,
`CustomerID` VARCHAR(5),
`EmployeeID` INTEGER,
`OrderDate` DATETIME,
`RequiredDate` DATETIME,
`ShippedDate` DATETIME,
`ShipVia` INTEGER,
`Freight` DECIMAL(10,4) DEFAULT 0,
`ShipName` VARCHAR(40),
`ShipAddress` VARCHAR(60),
`ShipCity` VARCHAR(15),
`ShipRegion` VARCHAR(15),
`ShipPostalCode` VARCHAR(10),
`ShipCountry` VARCHAR(15),
CONSTRAINT `PK_Orders` PRIMARY KEY (`OrderID`)
);
CREATE INDEX `OrderDate` ON `Orders` (`OrderDate`);
CREATE INDEX `ShippedDate` ON `Orders` (`ShippedDate`);
CREATE INDEX `ShipPostalCode` ON `Orders` (`ShipPostalCode`);
-- ------------------------------------------
-- Records of `Orders`
-- ------------------------------------------
INSERT INTO `Orders` VALUES
(10248, 'VINET', 5, '1996-07-04', '1996-08-01', '1996-07-16', 3, 32.38, 'Vins et alcools Chevalier', '59 rue de l''Abbaye', 'Reims', NULL, '51100', 'France'),
(10249, 'TOMSP', 6, '1996-07-05', '1996-08-16', '1996-07-10', 1, 11.61, 'Toms Spezialitäten', 'Luisenstr. 48', 'Münster', NULL, '44087', 'Germany'),
(10250, 'HANAR', 4, '1996-07-08', '1996-08-05', '1996-07-12', 2, 65.83, 'Hanari Carnes', 'Rua do Paço, 67', 'Rio de Janeiro', 'RJ', '05454-876', 'Brazil'),
(10251, 'VICTE', 3, '1996-07-08', '1996-08-05', '1996-07-15', 1, 41.34, 'Victuailles en stock', '2, rue du Commerce', 'Lyon', NULL, '69004', 'France'),
...
(11072, 'ERNSH', 4, '1998-05-05', '1998-06-02', NULL, 2, 258.64, 'Ernst Handel', 'Kirchgasse 6', 'Graz', NULL, '8010', 'Austria'),
(11073, 'PERIC', 2, '1998-05-05', '1998-06-02', NULL, 2, 24.95, 'Pericles Comidas clásicas', 'Calle Dr. Jorge Cash 321', 'México D.F.', NULL, '05033', 'Mexico'),
(11074, 'SIMOB', 7, '1998-05-06', '1998-06-03', NULL, 2, 18.44, 'Simons bistro', 'Vinbæltet 34', 'Kobenhavn', NULL, '1734', 'Denmark'),
(11075, 'RICSU', 8, '1998-05-06', '1998-06-03', NULL, 2, 6.19, 'Richter Supermarkt', 'Starenweg 5', 'Genève', NULL, '1204', 'Switzerland'),
(11076, 'BONAP', 4, '1998-05-06', '1998-06-03', NULL, 2, 38.28, 'Bon app''', '12, rue des Bouchers', 'Marseille', NULL, '13008', 'France'),
(11077, 'RATTC', 1, '1998-05-06', '1998-06-03', NULL, 2, 8.53, 'Rattlesnake Canyon Grocery', '2817 Milton Dr.', 'Albuquerque', 'NM', '87110', 'USA');

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

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

Syntax Problems? Insert Into

I'm creating an online store/database in MySQL, and I'm fairly new to the system.
Please tell me what is wrong with this statement:
CREATE TABLE IF NOT EXISTS Customers (
ID INT(15) NOT NULL AUTO_INCREMENT, -- Connects to table 'Orders' andOrderUserID
Email VARCHAR(100) NOT NULL,
PersonName VARCHAR(100) NOT NULL,
City VARCHAR(90) NOT NULL,
Zip INT(10),
CustomerState VARCHAR(50),
Address VARCHAR(200) NOT NULL,
Country VARCHAR(20),
Phone INT(50),
PRIMARY KEY (ID)
);
INSERT INTO Customers (ID, Email, PersonName, City, Zip, CustomerState, Address, Country, Phone) VALUES
(1, '1#gmail.com', 'Fred', 'Brisbane', 6543, 'QLD', '20 Not telling avenue', 'Australia', 932363626),
(2, '2#gmail.com', 'Mark', 'Perth', 3212, 'WA', ' 122 cralic road', 'Australia', 93223463221),
(3, '3#gmail.com', 'Leo', 'Melbourne', 2342, 'VIC', '90 normanly drive', 'Australia', 932645321),
(4, '4#gmail.com', 'Nick', 'Perth', 4294, 'WA', '44 happylane drive', 'Australia', 932222565621),
(5, '5#gmail.com', 'Mary', 'Perth', 6383, 'WA', '3 iverno crescent', 'Australia', 93365543321),
(6, '6#gmail.com', 'Julie', 'Perth', 9563, 'WA', '100 richmane lane', 'Australia', 9323456421),
(7, '7#gmail.com', 'Cynthia', 'Hobart', 3456, 'TAS', '12 trump avenue', 'Australia', 9322364641),
(8, '8#gmail.com', 'Mike', 'Albany', 7544, 'WA', '23 mapatazzie road', 'Australia', 9322236421),
(9, '9#gmail.com', 'Brett', 'Adelaide', 8953, 'SA', '983 chindes lane', 'Australia', 9322234651),
(10, '10#gmail.com', 'Paul', 'Sydney', 7853, 'VIC', '78 yives road', 'Australia', 932223463621),
1.) Always post which error you get when asking for help
2.) You left a comma , at the last line
3.) int(50) does not do what you think it does. It doesn't mean a number that has 50 digits. int means data type, and it will use 4 bytes. 50, in your case, means display length. Not storage length. int is 4 bytes. It can display up to 11 digits only (with minus sign included). Therefore, your int(50) doesn't make it 50 digits long, it will hold at maximum (2^32 - 1) = 4294967295.
Make your Phone a varchar
Update Last line with below line:
(10, '10#gmail.com', 'Paul', 'Sydney', 7853, 'VIC', '78 yives road', 'Australia', 932223463621);
add semicolon
Solution:
The problem is, you mentioned Phone field as integer and given values like 93223463221.
The integer value is greater than 2147483647, hence the error.
To solve,
alter table Customers modify column Phone varchar(50);
Use the above query to modify the Phone(Integer) filed as varchar field.
Then try to insert the values.

Normalizing Database to 3NF

I'm creating a database that as to have at least 5 tables in 3NF. From what I can gather the database is 3NF when I look at the specifications for a 3NF daabase, but I'm not 100% sure which is why I'm asking here, and if it's not I'm wondering how to make it 3NF, so I can move on and try test queries, triggers and procedures on the database.
I have been basing my work off this sample database, which I assume is in 3NF from my understanding.
Any help or advice at all is really appreciated as I've been having this problem for a few days now.
CREATE TABLE IF NOT EXISTS xbox (
game_id char(4) NOT NULL default '',
game_name varchar(32) default NULL,
developer varchar(32) default NULL,
PRIMARY KEY (game_id)
);
INSERT INTO xbox (game_id, game_name, developer) VALUES
('1001', 'Sunset Overdive', 'Insomniac Games'),
('1002', 'Quantum Break', 'Remedy Entertainment'),
('1003', 'Gears of War 4', 'The Coalition'),
('1004', 'Halo 5', '343 Industries'),
('1005', 'Forza 6', 'Turn10 Studios');
CREATE TABLE IF NOT EXISTS playstation (
game_id char(4) NOT NULL default '',
game_name varchar(32) default NULL,
developer varchar(32) default NULL,
PRIMARY KEY (game_id)
);
INSERT INTO playstation (game_id, game_name, developer) VALUES
('2001', 'Bloodborne', 'From Software'),
('2002', 'The Witness', 'Thekla'),
('2003', 'Destiny', 'Bungie'),
('2004', 'Black Ops 3', 'Treyarch'),
('2005', 'DriveClub', 'Evolution');
CREATE TABLE IF NOT EXISTS pc (
game_id char(4) NOT NULL default '',
game_name varchar(32) default NULL,
developer varchar(32) default NULL,
PRIMARY KEY (game_id)
);
INSERT INTO pc (game_id, game_name, developer) VALUES
('3001', 'Fallout 4', 'Bethesda'),
('3002', 'Tomb Raider', 'Crystal Dynamics'),
('3003', 'Overwatch', 'Blizzard'),
('3004', 'Rocket League', 'Psyonix'),
('3005', 'DiRT Rally', 'Codemasters');
CREATE TABLE IF NOT EXISTS nintendo (
game_id char(4) NOT NULL default '',
game_name varchar(32) default NULL,
developer varchar(32) default NULL,
PRIMARY KEY (game_id)
);
INSERT INTO nintendo (game_id, game_name, developer) VALUES
('4001', 'Mario Kart 8', 'Nintendo'),
('4002', 'Mario Maker', 'Nintendo'),
('4003', 'Mario Party 9', 'Nintendo'),
('4004', 'Bayonetta 2', 'Nintendo'),
('4005', 'Splatoon', 'Nintendo');
CREATE TABLE IF NOT EXISTS sales (
customer_id char(10) NOT NULL default '',
game_id char(4) NOT NULL default '',
quantity int(11) default NULL,
paid double default NULL,
payment varchar(32) default NULL,
PRIMARY KEY (game_id)
);
INSERT INTO sales (customer_id, game_id, quantity, paid, payment) VALUES
('1234567890', '1002', 1, 79.99, 'Debit'),
('0987654321', '2003', 1, 50, 'Credit'),
('1122334455', '2001', 2, 120, 'Cash'),
('6677889900', '4004', 3, 110.49, 'Cash'),
('1357924680', '3002', 1, 50, 'Credit');
CREATE TABLE IF NOT EXISTS products (
game_id char(10) default NULL,
platform varchar(32) default NULL,
stock int(11) default NULL,
price double default NULL,
PRIMARY KEY (game_id)
);
INSERT INTO products (game_id, platform, stock, price) VALUES
('1001', 'xbox', 33, 69.99),
('1002', 'xbox', 42, 79.99),
('1003', 'xbox', 50, 89.99),
('1004', 'xbox', 80, 59.99),
('1005', 'xbox', 10, 49.99),
('2001', 'playstation', 12, 55.99),
('2002', 'playstation', 44, 34.99),
('2003', 'playstation', 89, 45.99),
('2004', 'playstation', 65, 39.99),
('2005', 'playstation', 73, 19.99),
('3001', 'pc', 50, 69.99),
('3002', 'pc', 41, 49.99),
('3003', 'pc', 77, 59.99),
('3004', 'pc', 24, 19.99),
('3005', 'pc', 19, 24.99),
('4001', 'nintendo', 10, 19.99),
('4002', 'nintendo', 17, 39.99),
('4003', 'nintendo', 33, 28.99),
('4004', 'nintendo', 53, 34.99),
('4005', 'nintendo', 97, 15.99);
Since your xbox, pc, nintendo and playstation tables are all identical you may want to consider combining them into one and adding some sort of "type" column (or, as Prix mentioned, maybe have a one-to-many between platform and type in case the game can run on more than one platform).
With the current design you will start running into problems with any queries that are not type specific. If I am following your sample correctly, you are going to have to use the value of the products.platform column in order to determine which platform table contains the details you are looking for. This leads to row-at-a-time processing which is very inefficient.

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.