MySQL 5.6 Foreign Key Error Message - mysql

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

Related

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

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?

Column count doesn't match value count? But it does

CREATE TABLE invoices(
invoice_id INT PRIMARY KEY,
category_id INT NOT NULL,
supplier_id INT NOT NULL,
invoice_due_date VARCHAR(12),
invoice_supplier VARCHAR(255) NOT NULL,
invoice_contact VARCHAR(255) NOT NULL,
invoice_amount INT,
invoice_paid BOOL DEFAULT FALSE,
CONSTRAINT invoice_fk_supplier
FOREIGN KEY(supplier_id)
REFERENCES suppliers(supplier_id),
CONSTRAINT invoice_fk_category
FOREIGN KEY(category_id)
REFERENCES categories(category_id)
);
INSERT INTO invoices(invoice_id, category_id, supplier_id,
invoice_supplier, invoice_due_date, invoice_contact, invoice_amount,
invoice_paid) VALUES
(1, 2, 1, "Pepsi" '12-24-2017', 'James Hatfield', 23500, FALSE),
(2, 2, 2, "Ragu", '12-20-2017', 'Mike Richards', 8650, FALSE),
(3, 2, 3, "Miguel's Produce", '12-18-2017', 'Miguel Profesa', 6750,
FALSE),
(4, 2, 4, "Butch's Butcher Shop", '12-15-2017', 'Rick Santana', 9550,
FALSE),
(5, 2, 5, "Cafe Carmen", '12-04-2017', 'Carmen San Diego', 1250, FALSE);
I am using MySQL WorkBench 6.3, and I keep getting this error
"Error Code: 1136. Column count doesn't match value count at row 1"
whenever I am trying to run my INSERT statement to add data to the database. I have no issues with my other tables, only this one. However, when I was looking up this error, it seems that many times the error comes down to not having a matching number of values to the records, but I have triple checked that I have 8 fields and 8 values.
If anyone could help me out or explain it at all, it would be much appreciated as this has had me stumped for a few hours.
Cheers!
First and foremost "Pepsi" '12-24-2017' has no comma in between ..typo error
(1, 2, 1, "Pepsi" '12-24-2017', 'James Hatfield', 23500, FALSE),
SEcondly your fourth column is VARCHAR(12) & not VARCHAR(255)
Primary key insertion has a lot of conflict...to be on safe side...keep PK auto
CREATE TABLE invoices(
invoice_id INT NOT NULL AUTO_INCREMENT,
category_id INT NOT NULL,
supplier_id INT NOT NULL,
invoice_due_date VARCHAR(255),
invoice_supplier VARCHAR(255) NOT NULL,
invoice_contact VARCHAR(255) NOT NULL,
invoice_amount INT,
invoice_paid BOOL DEFAULT FALSE,
CONSTRAINT invoice_fk_supplier
FOREIGN KEY(supplier_id)
REFERENCES suppliers(supplier_id),
CONSTRAINT invoice_fk_category
FOREIGN KEY(category_id)
REFERENCES categories(category_id)
);
and then do an insert like..
INSERT INTO invoices( category_id, supplier_id,
invoice_supplier, invoice_due_date, invoice_contact, invoice_amount,
invoice_paid) VALUES
( 2, 1, "Pepsi", "12-24-2017", "James Hatfield", 23500, FALSE)

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.