Related
MySQL is a new language to me and I struggle with selecting more data from my loans table when I do this query:
My objective is to print all elements of the Loans table that match the Bank IDs, all I get is outputs 1-10 where I have over 13 elements in my loans table.
EDIT 1: Bank Table serves as a link between all tables, I know the problem resides in my DML query however cluelessly not sure what to do.
When running my query, only matching primary key to foreign key appears. That is if Bank ID is 1 and Loans ID is 1 it shows, but when Bank ID is 1 and Loans ID is 13 it does not appear in the query.
Please save your criticism, as mentioned above, my experience is green.
My DML:
SELECT bank.bankID, bankcustomer.FirstName, bankcustomer.LastName, loans.FirstPaymentDate
FROM bank
JOIN bankcustomer ON bank.bankID = bankcustomer.customerID
JOIN loans ON loans.LoansID = bank.bankID;
Tables DDL:
CREATE TABLE bankCustomer(
CustomerID int(11) NOT NULL AUTO_INCREMENT,
FirstName varchar(20) DEFAULT NULL,
MiddleName varchar(20) DEFAULT NULL,
LastName varchar(20) DEFAULT NULL,
Address_Line1 varchar(50) DEFAULT NULL,
Address_Line2 varchar(50) DEFAULT NULL,
City varchar(20) DEFAULT NULL,
Region varchar(20) DEFAULT NULL,
PostCode varchar(20) DEFAULT NULL,
Country varchar(30) DEFAULT NULL,
DateOfBirth DATE DEFAULT NULL,
telephoneNumber int(13) DEFAULT 0,
openingAccount int CHECK (openingAccount >= 50),
PRIMARY KEY (CustomerID),
KEY CustomerID (CustomerID)
) ENGINE=INNODB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
CREATE TABLE bank(
BankID int(11) NOT NULL AUTO_INCREMENT,
customerID int,
PRIMARY KEY (BankID),
FOREIGN KEY (CustomerID) REFERENCES bankCustomer(CustomerID) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
CREATE TABLE loans(
LoansID int(11) NOT NULL AUTO_INCREMENT,
BankID int,
PaymentRate int(100) DEFAULT 300,
NumOfMonthlyPayments int(12) DEFAULT NULL,
FirstPaymentDate DATE DEFAULT NULL,
MonthlyDueDate DATE DEFAULT NULL,
PRIMARY KEY (LoansID),
FOREIGN KEY (BankID) REFERENCES bank(BankID) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
INSERT DML's:
INSERT INTO bank (BankID, CustomerID) VALUES (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10);
INSERT INTO loans (LoansID, BankID, PaymentRate, NumOfMonthlyPayments, FirstPaymentDate, MonthlyDueDate) VALUES (1, 1, 400, 12, '2008-02-03', '2008-03-25'),
(11, 1, 150, 10, '2008-02-04', '2008-04-25'),
(12, 1, 150, 10, '2008-02-07', '2008-04-25'),
(2, 2, 100, 20, '2011-04-01', '2011-04-25'),
(3, 3, 85, 5, '2015-07-03', '2015-08-25')...
Thank you all for your dear help, I managed to resolve my issue. The problem was the order of JOINing clauses.
SELECT loans.LoansID, bankcustomer.FirstName, customerbankcard.AccountNumber, loans.FirstPaymentDate
FROM bank
JOIN loans ON loans.BankID = bank.bankID
JOIN bankcustomer ON bankcustomer.customerID = bank.customerID
JOIN customerbankcard ON customerbankcard.bankID = bank.bankID
GROUP BY loans.LoansID ASC;
The outcome was to avoid loop, repeating wrongly assigned account numbers with customers whose IDs did not match.
If you want to select all tables use *. Also, you are joining tables incorrectly.
SELECT bank.*, bankcustomer.*, loans.*
FROM bank
JOIN bankcustomer ON bank.customerID = bankcustomer.customerID --Since you want to join data on customer ID you select custemerID in both tables
JOIN loans ON loans.BankID = bank.bankID; --The same problem here when joining tables
Goodluck and happy coding!
Firstly, joins could only be used between the tables when the columns are common between them (though they might have different names in different tables). That is why the concept of foreign key is of paramount importance as it references the column to the referenced table as you have duly done in your DDL commands.
Secondly, try using semicolon (;) as it denotes the end of any command and might get you out of the looping.
I have created a table but when i try to insert values I get an error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (classicmodels.complaints, CONSTRAINT complaints_ibfk_1 FOREIGN KEY (employeeHandling) REFERENCES customers (customerNumber))
I'm not entirely sure what this means so an explanation would be very helpful! Thank you!
CREATE TABLE `complaints` (
`complaintNumber` INT UNIQUE AUTO_INCREMENT,
`customerNumber` INT NOT NULL,
`orderNumber` INT,
`employeeHandling` INT NOT NULL,
`startDate` DATE NOT NULL,
`closeDate` DATE,
`complaintType` VARCHAR(250) NOT NULL,
`details` TEXT,
`resolution` TEXT,
`status` VARCHAR(250) NOT NULL,
PRIMARY KEY (`complaintNumber`),
FOREIGN KEY (`employeeHandling`) REFERENCES customers (`customerNumber`),
FOREIGN KEY (`customerNumber`) REFERENCES employees (`employeeNumber`),
FOREIGN KEY (`orderNumber`) REFERENCES orders (`orderNumber`)
);
INSERT INTO complaints
VALUES
(NULL, 173, NULL, 1323, '2005-03-27', NULL, 'Late Shipment', 'Customer claims shipment came in 2 weeks late. Requests discount/partial refund.', NULL, 'New'),
(NULL, 260, 10283, 1323, '2004-09-18', '2004-09-22', 'Damaged Shipment', 'Motorcycle had broken axle. Requests replacement, partial refund.', 'Axle sent and installed. Customer took $1000 refund', 'Closed'),
(NULL, 385, 10108, 1621, '2003-04-22', '2003-04-23', 'Missing Item', 'Customer claims item not included in shipment. Requests shipment.', 'Customer miscounted shipment stock. No action required.', 'Closed'),
(NULL, 471, 10265, 1611, '2004-07-10', '2004-08-10', 'Unclear', 'Customer disatisfied with shipment quality(?), though inventory not damaged. Requests refund.', 'Customer failed to provide specific reasons. Complaint ticket closed after 1 month of idle time.', 'Closed');
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to create some tables and populate them with dummy data and i've come across this problem that's making me scratch my head to no end as i don't understand it.
Here are the tables:
CREATE TABLE `DRIVER` (
`dr_ID` INT NOT NULL,
`dr_title` VARCHAR(15) NOT NULL,
`dr_fname` VARCHAR(45) NOT NULL,
`dr_lname` VARCHAR(45) NOT NULL,
`dr_DOB` DATETIME NOT NULL,
`dr_licenceNo` VARCHAR(45) NOT NULL,
`dr_phone` VARCHAR(15) NOT NULL,
`dr_email` VARCHAR(45) NOT NULL,
PRIMARY KEY (`dr_ID`));
CREATE TABLE `VEHICLE` (
`veh_ID` INT NOT NULL,
`veh_reg` VARCHAR(15) NOT NULL,
`veh_make` VARCHAR(45) NOT NULL,
`veh_model` VARCHAR(45) NOT NULL,
`veh_mileage` INT NOT NULL,
`veh_MOTdate` DATETIME NOT NULL,
`veh_servicedate` DATETIME NOT NULL,
PRIMARY KEY (`veh_ID`));
CREATE TABLE `DELIVERY` (
`del_ID` VARCHAR(45) NOT NULL,
`del_date` DATETIME NOT NULL,
`del_time` DATETIME NOT NULL,
`VEHICLE_veh_ID` INT NOT NULL,
`DRIVER_dr_ID` INT NOT NULL,
INDEX `fk_VEHICLE_has_DRIVER_DRIVER1_idx` (`DRIVER_dr_ID` ASC),
INDEX `fk_VEHICLE_has_DRIVER_VEHICLE1_idx` (`VEHICLE_veh_ID` ASC),
PRIMARY KEY (`del_ID`),
CONSTRAINT `fk_VEHICLE_has_DRIVER_VEHICLE1`
FOREIGN KEY (`VEHICLE_veh_ID`)
REFERENCES `VEHICLE` (`veh_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_VEHICLE_has_DRIVER_DRIVER1`
FOREIGN KEY (`DRIVER_dr_ID`)
REFERENCES `DRIVER` (`dr_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
INSERT INTO DELIVERY(del_ID, del_date, del time, VEHICLE_veh_ID, DRIVER_dr_ID) VALUES
(01, '2016-02-06', '09:30:00', 03, 05),
(02, '2016-02-06', '09:30:00', 01, 02),
(03, '2016-02-07', '09:30:00', 02, 03),
(04, '2016-02-07', '09:30:00', 04, 01),
(05, '2016-02-07', '09:30:00', 10, 04),
(06, '2016-02-08', '09:30:00', 07, 01),
(07, '2016-02-08', '09:30:00', 08, 02),
(08, '2016-02-08', '09:30:00', 09, 03),
(09, '2016-02-08', '09:30:00', 02, 04),
(10, '2016-02-09', '09:30:00', 03, 05);
I inserted data into DRIVER and VEHICLE with no issues but when i try to insert data into DELIVERY i get the following error:
ERROR 1064 (42000): 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 'time, VEHICLE_veh_ID, DRIVER_dr_ID) VALUES (01,
'2016-02-06', '09:30:00', 03, 05') at line 1
I'm using the same insert pattern that i've used for previous tables and the values match their corresponding types. I keep going through it over and over again and i can't see what i've done wrong. Any help/suggestions?
del time
Should be one word. You wrote "del_time" when you created the table.
Here is my table and I keep getting this error. Everything is good to go until I execute the code that I have put in bold at the bottom. Im really close to completing this table but ive tried everything to solve this error but it keeps coming up.
Please Help me
Thank You`
UPDATE
I took your guys suggestions and changed the inserted data now im getting an error 1136 which is column doesnt match value count for row 1 which is visit ID so its a datatype problem but ive tried everything and I cant figure it out IM SO CLOSE TO BEING DONE
PLEASE HELP!
Create Schema Visit;
create table roomtableS(
RoomID char (2) not null,
RoomNum char (2) not null,
Charge integer not null,
CONSTRAINT RoomTable_PK Primary Key(RoomID));
Insert into roomtableS values
('01','1A',125.00),
('02','1A',150.00),
('03','1A',100.00),
('04','1A',200.00),
('05','2B',150.00),
('06','2B',125.00),
('07','3C',200.00),
('08','3C',125.00),
('09','3C',100.00);
SELECT * FROM ROOMTABLES;
create table PATIENT(
PatientID char(5) not null,
PatientName Char(25) not null,
PatientEmail Char(30) null,
PatientPhoneNumber Char(10) null,
PatientAddress Char(100) null,
constraint PATIENT_PK Primary key(PatientID));
insert PATIENT values
('P1', 'Bruce Willis', 'bwillis#mail.org', '2022223333', '1111 Cosmic dr'),
('P2', 'Demi Moore', 'moore#email.net', '2021113333', '1112 Cosmic dr'),
('P3', 'Andre Agassi', 'agassi#mail.org', '2023333333', '1113 Cosmic dr'),
('P4', 'Jet Lee', 'jetlee#email.net', '2023334444', '1114 Chinatown ct'),
('P5', 'Jim Carey', 'carey#email.net', '2023335555', '1115 United dr'),
('P6', 'Bruce Lee', 'bruce#gmail.com', '2023336666', '1115 Chinatown ct');
select* From PATIENT;
Create table SERVICETable(
ServiceID Char (5) not null,
ServiceTreatment Char(25) not null,
ServiceCost numeric not null,
constraint SERVICE_PK Primary Key(ServiceID));
insert SERVICETable values
('S1','Sore throat', 10.00),
('S2', 'Fever', 15.00),
('S3', 'Headache', 10.00),
('S4', 'Blood pressusre', 20.00),
('S5', 'Yearly checkup', 30.00),
('S6', 'Common cold', 15.00);
select* from SERVICETable;
Create Table doctortable(
DocID char (5) NOT NULL,
DoctorFirstName char(15) Not NULL,
DoctorLastName char (15) Not Null,
DoctorPhone char (15) Not Null,
CONSTRAINT DoctorTable_PK Primary Key(DocID));
INSERT INTO doctortable values
('D1','Tim','Edward','555-123-4567'),
('D2','Andy','Smith','888-777-6666'),
('D3','John','Smith','222-321-7654');
Select * From doctortable;
Create Table visit(
VisitID char (2) not Null,
PatientID Char (5) not null,
DocID Char (5) not null,
ServiceID Char (5) not Null,
RoomID char (2) not Null,
Visit date not null,
CONSTRAINT VISIT_PK PRIMARY KEY (VisitID));
Alter table Visit
add foreign key (PatientID)
references Patient (PatientID);
Alter table Visit
add foreign key (DocID)
references doctortable (DocID);
Alter table Visit
add foreign key (ServiceID)
references ServiceTable (ServiceID);
Alter table Visit
add foreign key (RoomID)
references roomtableS (RoomID);
Insert into Visit (VisitID,RoomID,ServiceID,PatientID,Visit) values
**('1','P1','D1','S1','05','2014-01-03'),
('2','P2','D2','S2','01','2014-01-10'),
('3','P3','D1','S3','02','2014-01-10'),
('4','P4','D2','S4','07','2014-01-15'),
('5','P1','D3','S2','08','2014-01-10'),
('6','P5','D3','S5','03','2014-02-02'),
('7','P4','D1','S6','06','2014-01-10'),
('8','P3','D2','S5','03','2014-02-03'),
('9','P2','D3','S6','01','2014-02-04'),
('10','P3','D1','S2','06','2014-02-04'),
('11','P5','D2','S4','04','2014-02-05'),
('12','P4','D1','S5','09','2014-02-06');**
Select * from Visit;
Thank You!
Your insert query into Visit table is like this:
Insert Visit Values
('1','P1','D1','S1','2B','2014-01-03'),
Values are expected to be in the order of
(VisitID, RoomID, ServiceID, PatientID, DocID, Visit)
But they seem to be in a different order.
Change the insert statement to include column names.
Insert Visit
(VisitID, PatientID, DocID, ServiceID, RoomID, Visit)
Values
('1','P1','D1','S1','2B','2014-01-03'),
And the values, '2B' being inserted into 'RoomID' column seem to be 'RoomNum' values but not 'RoomID' values. Change it to '05', or '06'. Such change has to be done in all other inputs for the column.
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.