I am trying to create a database that holds staff information such as their names, timesheets, holidays booked etc and also information about the projects the are carrying out and what companies the projects are for. My code is below:
CREATE TABLE IF NOT EXISTS tblcompany (
companyid INT(11) UNSIGNED NOT NULL,
custfirst VARCHAR(50),
custlast VARCHAR(50),
company VARCHAR(50),
custphone VARCHAR(50),
custemail VARCHAR(50),
PRIMARY KEY (companyid),
INDEX (companyid),
CONSTRAINT FOREIGN KEY (companyid)
REFERENCES tblproject (companyid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblemployee (
employeeid INT(11) UNSIGNED NOT NULL,
employeefirst VARCHAR(50),
employeelast VARCHAR(50),
employeephone VARCHAR(50),
employeeemail VARCHAR(50),
PRIMARY KEY (employeeid),
INDEX (employeeid),
CONSTRAINT FOREIGN KEY (employeeid)
REFERENCES tbltimesheet (employeeid),
CONSTRAINT FOREIGN KEY (employeeid)
REFERENCES tblholiday (employeeid),
CONSTRAINT FOREIGN KEY (employeeid)
REFERENCES tblannualleave (employeeid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblholiday (
holidayid INT(11) UNSIGNED NOT NULL,
employeeid INT(11) UNSIGNED NOT NULL,
holidayfrom DATE,
holidayto DATE,
holidayhalfday BOOLEAN,
holidayreason VARCHAR(50),
INDEX (employeeid),
PRIMARY KEY (holidayid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblannualleave (
annualleaveid INT(11) UNSIGNED NOT NULL,
employeeid INT(11) UNSIGNED NOT NULL,
annualleavetaken INT(11),
annualleaveremain INT(11),
anuualleavetotal INT(11),
INDEX (employeeid),
PRIMARY KEY (annualleaveid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblproject (
projectid INT(11) UNSIGNED NOT NULL,
projectname VARCHAR(50),
projecttype VARCHAR(50),
companyid INT(11) UNSIGNED NOT NULL,
projectnotes VARCHAR(50),
PRIMARY KEY (projectid),
INDEX (projectid),
CONSTRAINT FOREIGN KEY (projectid)
REFERENCES tbltimesheet (projectid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tbltimesheet (
timesheetid INT(11) UNSIGNED NOT NULL,
employeeid INT(11) UNSIGNED NOT NULL,
projectid INT(11) UNSIGNED NOT NULL,
timesheetdate DATE,
timesheethours INT(11),
timesheetnotes VARCHAR(50),
INDEX (employeeid),
PRIMARY KEY (timesheetid)
) ENGINE=InnoDB;
I have been looking around and have tried everything, it is probably something so simple. I have changed all the datatypes to similar ones to see if this would solve the problem butno luck. The error code I get is:
Error Code: 1215. Cannot add foreign key constraint
0.063 sec
CREATE TABLE IF NOT EXISTS tblcompany ( companyid INT(11) UNSIGNED
NOT NULL, custfirst VARCHAR(50), custlast VARCHAR(50),
company VARCHAR(50), custphone VARCHAR(50), custemail
VARCHAR(50), PRIMARY KEY (companyid), INDEX (companyid),
CONSTRAINT FOREIGN KEY (companyid) REFERENCES tblproject
(companyid) ) ENGINE=InnoDB
11:15:57 CREATE TABLE IF NOT EXISTS tblcompany ( companyid INT(11)
UNSIGNED NOT NULL, custfirst VARCHAR(50), custlast
VARCHAR(50), company VARCHAR(50), custphone VARCHAR(50),
custemail VARCHAR(50), PRIMARY KEY (companyid), INDEX
(companyid), CONSTRAINT FOREIGN KEY (companyid) REFERENCES
tblproject (companyid) ) ENGINE=InnoDB Error Code: 1215. Cannot add
foreign key constraint 0.063 sec
Thank you for looking..
Create the table tblproject first before you reference it.
Besides the wrong table order,you need either a primary or unique key on referenced columns.
SQL fiddle
I think you will solve your problem creating your tables in the opposite ordersm, otherwise you will have the same issue with tblemployee.
A Foreigh Key needs that the reference table exists already.
You cannot create a foreign key when the table it references does not yet exist. You can always create the foreign key later.
You must first create the tables containing the referenced fields, after you create the table with the foreign key.
You could also create first all the tables, and create all foreign keys in a second step.
Related
I wrote a sql file to create a Database and add tables in that database.
Here is the code:
CREATE SCHEMA `employee_details`;
CREATE TABLE `employee_details`.`employee` (
`emp_id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45),
`dob` DATE,
`joiningdate` DATE,
`designation_id` INT,
`gender` VARCHAR(45),
`address` VARCHAR(90),
`manager_id` INT,
PRIMARY KEY (`emp_id`)
);
CREATE TABLE `employee_details`.`designation` (
`designation_id` INT NOT NULL AUTO_INCREMENT,
`designation` VARCHAR(45),
`dept_id` INT,
`salary` FLOAT,
PRIMARY KEY (`designation_id`)
);
CREATE TABLE `employee_details`.`department` (
`dept_id` integer NOT NULL AUTO_INCREMENT,
`dept_name` VARCHAR(45),
PRIMARY KEY (`dept_id`)
);
CREATE TABLE `employee_details`.`rating` (
`emp_id` INT,
`emp_rating` INT,
`add_perks` FLOAT,
`experience` INT
);
CREATE TABLE `employee_details`.`project_assign` (
`emp_id` INT,
`project_id` INT
);
CREATE TABLE `employee_details`.`project` (
`project_id` INT NOT NULL AUTO_INCREMENT,
`project_name` VARCHAR(45),
`project_dept` INT,
PRIMARY KEY (`project_id`)
);
ALTER TABLE employee
ADD FOREIGN KEY (emp_id) REFERENCES rating(emp_id);
ALTER TABLE employee
ADD FOREIGN KEY (emp_id) REFERENCES project_assign(emp_id);
ALTER TABLE employee
ADD FOREIGN KEY (emp_id) REFERENCES employee(manager_id);
ALTER TABLE designation
ADD FOREIGN KEY (designation_id) REFERENCES employee(designation_id);
ALTER TABLE designation
ADD FOREIGN KEY (dept_id) REFERENCES department(dept_id);
ALTER TABLE department
ADD FOREIGN KEY (dept_id) REFERENCES project(project_dept);
ALTER TABLE project
ADD FOREIGN KEY (project_id) REFERENCES project_assign(project_id);
When I execute that sql file, I get below error:
15:16:50 ALTER TABLE employee ADD FOREIGN KEY (emp_id) REFERENCES rating(emp_id) Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'employee_ibfk_1' in the referenced table 'rating' 0.000 sec
I checked data types of emp_id in employee and rating. They are same. How can I fix this error?
All your foreign key relationships are backwards. It should be:
ALTER TABLE rating
ADD FOREIGN KEY (emp_id) REFERENCES employee(emp_id);
and similar for all the other foreign keys.
So I don't know why i cant add the foreign constraint in the table ORDER_LINE, i made sure all the types are correct. Please help, it keeps on giving me the error
Error Code: 1215. Cannot add foreign key constraint
CREATE TABLE IF NOT EXISTS Customer (
Customer_ID int NOT NULL AUTO_INCREMENT,
Customer_Name VARCHAR(50) NOT NULL,
Customer_Age INT UNIQUE,
Customer_Address VARCHAR(255),
Customer_City VARCHAR(255),
Customer_State VARCHAR(50),
Customer_Zip VARCHAR(20),
PRIMARY KEY(Customer_ID)
);
CREATE TABLE IF NOT EXISTS Sales_order (
Order_ID int AUTO_INCREMENT,
Order_date DATE,
Customer_ID int,
PRIMARY KEY(Order_ID),
FOREIGN KEY(Customer_ID) REFERENCES Customer(Customer_ID) ON DELETE
CASCADE
);
CREATE TABLE IF NOT EXISTS Products (
Product_ID int AUTO_INCREMENT,
Product_Description VARCHAR(255),
Product_Finish VARCHAR(50),
Standard_Price DECIMAL,
Product_Line_ID INT,
PRIMARY KEY(Product_ID)
);
CREATE TABLE IF NOT EXISTS ORDER_LINE (
Order_ID int,
Product_ID int,
Ordered_Quantity int,
PRIMARY KEY(Order_ID, Product_ID),
FOREIGN KEY(Order_ID) REFERENCES Sales_order(Order_ID) ON DELETE SET NULL,
FOREIGN KEY(Product_ID) REFERENCES Products(Product_ID)
);
This might be because primary key columns are made NOT NULL, so your ON DELETE SET NULL is trying to set an invalid value.
EDIT: In fact, I just tested and that does seem to be the issue -- it creates the table if I remove either the SET NULL or the primary key.
i have this script running on sql, but i need to optimize it to mysql using the workbench, but it shows me an error in the foreign key and i don't know how to change it.
create table EspecialidadesMedicas(
IdEspecialidad int(4) primary key,
DescripcionEspecialidad varchar(30));
create table Doctores(
IdDoctor int(5) PRIMARY KEY,
NombreDoctor varchar(30),
Salario int(12.2),
Especialidad int(4),citascitas
Especialidad FOREIGN KEY references EspecialidadesMedicas(IdEspecialidad));
The following is working syntax:
create table EspecialidadesMedicas (
IdEspecialidad int(4) primary key,
DescripcionEspecialidad varchar(30)
);
create table Doctores(
IdDoctor int(5) PRIMARY KEY,
NombreDoctor varchar(30),
Salario int(12),
Especialidad int(4),
citascitas varchar(30),
constraint fk_Especialidad FOREIGN KEY (Especialidad) references EspecialidadesMedicas(IdEspecialidad)
);
I'm getting an ERROR 1064 (42000) at line 21, which is VIN_Number in Vehicle table. Entity Inventory gets built without a problem, VIN_Number is of type varchar(17) for all occurrences. I believe the tables are being built in the correct order. I can't find any spelling or punctuation errors. I'm out of ideas of things I should checked. What is it that I'm missing?
Note: I getting an error for Invoice as well, but I know that it can't be created until Vehicle gets created.
ALTER TABLE Vehicle DROP FOREIGN KEY fk_Veh_Vehicle_TypeID;
ALTER TABLE Inventory DROP FOREIGN KEY fk_Inv_Vehicle_TypeID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_Customer_ID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_Sales_Person_ID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_VIN_Number;
DROP TABLE IF EXISTS Vehicle, VehicleType,
Invoice, Customer, SalesPerson, Inventory;
CREATE TABLE VehicleType (
Vehicle_TypeID int NOT NULL,
Veh_Make varchar(15),
Veh_Model varchar(15),
Veh_Year int,
PRIMARY KEY (Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Vehicle (
VIN_Number varchar(17) NOT NULL,
Vehicle_TypeID int NOT NULL,
Condition varchar(10),
Color varchar(8),
PRIMARY KEY (VIN_Number),
CONSTRAINT fk_Veh_Vehicle_TypeID FOREIGN KEY(Vehicle_TypeID)
REFERENCES VehicleType(Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Inventory (
Stock_ID int NOT NULL,
Vehicle_TypeID int NOT NULL,
Quantity int,
PRIMARY KEY (Stock_ID),
CONSTRAINT fk_Inv_Vehicle_TypeID FOREIGN KEY (Vehicle_TypeID)
REFERENCES VehicleType(Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Customer (
Customer_ID varchar(10) NOT NULL,
Cus_LastName varchar(15),
Cus_FirstName varchar(15),
Cus_Street varchar(20),
Cus_City varchar(15),
Cus_Zip varchar(5),
Cus_Phone varchar(10),
PRIMARY KEY (Customer_ID)
) Engine=InnoDB;
CREATE TABLE SalesPerson (
Sales_Person_ID varchar(10) NOT NULL,
Sal_LastName varchar(15),
Sal_FirstName varchar(15),
Sal_Street varchar(15),
Sal_City varchar(15),
Sal_Zip varchar(5),
Sal_Phone varchar(10),
Sal_Years_Worked int,
Sal_Commission_Rate float(4),
PRIMARY KEY (Sales_Person_ID)
) Engine=InnoDB;
CREATE TABLE Invoice (
Invoice_ID varchar(10) NOT NULL,
Customer_ID varchar(10) NOT NULL,
Sales_Person_ID varchar(10) NOT NULL,
VIN_Number varchar(17) NOT NULL,
Price float(10),
PRIMARY KEY (Invoice_ID),
CONSTRAINT fk_Customer_ID FOREIGN KEY (Customer_ID)
REFERENCES Customer(Customer_ID),
CONSTRAINT fk_Sales_Person_ID FOREIGN KEY (Sales_Person_ID)
REFERENCES SalesPerson(Sales_Person_ID),
CONSTRAINT fk_VIN_Number FOREIGN KEY (VIN_Number)
REFERENCES Vehicle(VIN_Number)
) Engine=InnoDB;
In the definition of the Vehicle table you have a column named condition which is a reserved keyword in MySQL (reference). Either use another name for the column or enclose it in backticks like this: `condition`
Using keywords (reserved or not) for object names is generally something you want to avoid.
CREATE TABLE tblTransaction (
strTransCode VARCHAR(50) NOT NULL,
dtmTransDate datetime,
strTransDesc VARCHAR(50) NOT NULL,
dblTransAmt double,
intVoucRefCodeTrans INT,
FOREIGN KEY (intVoucRefCodeTrans) REFERENCES tblVoucher (intVoucRefCode) ON DELETE RESTRICT ON UPDATE CASCADE,
PRIMARY KEY (strTransCode)
)ENGINE=InnoDB;
CREATE TABLE tblVoucher (
intVoucRefCode INT,
strVoucRefDesc VARCHAR(50) NOT NULL,
dtmVoucDate datetime,
PRIMARY KEY (intVoucRefCode)
)ENGINE=InnoDB;
these are my tables I don't know why it displays "Cannot add foreign key constraint" please help
First create tblVoucher table then reference it in tblTransaction table
CREATE TABLE tblVoucher (
intVoucRefCode INT,
strVoucRefDesc VARCHAR(50) NOT NULL,
dtmVoucDate datetime,
PRIMARY KEY (intVoucRefCode)
)ENGINE=InnoDB;
CREATE TABLE tblTransaction (
strTransCode VARCHAR(50) NOT NULL,
dtmTransDate datetime,
strTransDesc VARCHAR(50) NOT NULL,
dblTransAmt double,
intVoucRefCodeTrans INT,
FOREIGN KEY (intVoucRefCodeTrans) REFERENCES tblVoucher (intVoucRefCode) ON DELETE RESTRICT ON UPDATE CASCADE,
PRIMARY KEY (strTransCode)
)ENGINE=InnoDB;
DEMO