Getting error while altering table in MySQL - mysql

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.

Related

Cannot add foreign keys constraint

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

Confusing cannot add foreign key constraint error

Ok, maybe it's late and I'm being stupid, but I can't seem to figure out why I'm getting a Cannot add Foreign Key Constraint error for the following query
DROP TABLE IF EXISTS People_Lordships;
CREATE TABLE People_Lordships
(
Id INT PRIMARY KEY AUTO_INCREMENT,
PersonId INT NOT NULL,
LordshipId INT NOT NULL,
AssumedDate Date,
AbdicatedDate Date
);
DROP TABLE IF EXISTS People_Lordships_Current;
CREATE TABLE People_Lordships_Current
(
Id INT PRIMARY KEY AUTO_INCREMENT,
People_LordshipsId INT NOT NULL,
LordShipId INT NOT NULL,
CONSTRAINT Fk_People_Lordships_Current_People_LordshipsId_LordshipId
FOREIGN KEY (`LordshipId`,`People_LordshipsId`)
REFERENCES People_Lordships (`LordshipId`,`Id`)
ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT UQ_People_Lordships_Current_LordshipId
UNIQUE KEY (`LordshipId`)
);
And yes, it is a database about noble titles... it's a long story
There is no column LordshipId in table People_Lordships.
Your foreign key definition attempts to reference a column that doesn't exist.
REFERENCES People_Lordships (`LordshipId`,`Id`)
^^^^^^^^^^^^
Figured this one out.
It turns out MySQL cannot add a foreign key constraint against a column that is not the first column in an index.
The following will work
DROP TABLE IF EXISTS People_Lordships;
CREATE TABLE People_Lordships
(
Id INT PRIMARY KEY AUTO_INCREMENT,
PersonId INT NOT NULL,
LordshipId INT NOT NULL,
AssumedDate Date,
AbdicatedDate Date,
INDEX Idx_LordshipId (LordshipId)
);
DROP TABLE IF EXISTS People_Lordships_Current;
CREATE TABLE People_Lordships_Current
(
Id INT PRIMARY KEY AUTO_INCREMENT,
People_LordshipsId INT NOT NULL,
LordShipId INT NOT NULL,
CONSTRAINT Fk_People_Lordships_Current_People_LordshipsId_LordshipId
FOREIGN KEY (`LordshipId`,`People_LordshipsId`)
REFERENCES People_Lordships (`LordshipId`,`Id`)
ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT UQ_People_Lordships_Current_LordshipId
UNIQUE KEY (`LordshipId`)
);

Foreign Key Unexpected

I'm using MySQL workbench and I am trying to create a table consist of foreign key using SQL Query. I am having problem with the Foreign part.
create table employee_position
(
ePID int primary key,
ePName varchar(45) not null,
eID int foreign key references employee_profile(eID)
)
Your syntax is wrong. Try:
create table employee_position
(
ePID int primary key,
ePName varchar(45) not null,
eID int,
foreign key (keyname) references employee_profile(eID)
)
For more information see the mysql documentation
create table employee_position
(
ePID int primary key,
ePName varchar(45) not null,
eID int,
foreign key (eID) references employee_profile(eID)
)
SQLFiddle demo
Check FOREIGN KEYS in MySQL.
Try this:
CREATE TABLE employee_position
(
ePID INT NOT NULL AUTO_INCREMENT,
ePName VARCHAR(45) NOT NULL,
eID INT NOT NULL,
PRIMARY KEY (ePID),
KEY CustomerID (eID),
CONSTRAINT FK_employee_position_EP
FOREIGN KEY (eID)
REFERENCES employee_profile (eID) ON DELETE CASCADE ON UPDATE CASCADE
);

MySQL error 1215, what am I doing wrong?

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.

Dropping tables mySql

I am having terrible trouble figuring out the order these tables should be dropped in for my script I will post the script now, If anyone could help with the order they should be dropped in it would be a great help
drop table Registered_Student;
drop table EducateYou_VideoRating;
drop table EducateYou_Video;
drop table EducateYou_Violation;
drop table EducateYou_Member;
drop table Violation_Type;
drop table EducateYou_Comment;
drop table EducateYou_FollowList;
drop table EducateYou_Group;
drop table EducateYou_Admin;
commit;
create table EducateYou_Violation
(
violationId number (9),
violationStatus char(1) DEFAULT 'X',
videoId number(9),
groupId number (9),
commentId number(9),
CONSTRAINT pk_violationId PRIMARY KEY (violationId),
CONSTRAINT fk_x_videoId FOREIGN KEY (videoId) REFERENCES EducateYou_Video,
CONSTRAINT fk_y_groupId FOREIGN KEY (groupId) REFERENCES EducateYou_Group,
CONSTRAINT fk_z_commentId FOREIGN KEY (commentId) REFERENCES EducateYou_Comment
);
create table EducateYou_Video(
videoId number(9),
videoRef varchar2(50) NOT NULL,
videoTitle varchar2(15) NOT NULL,
uploadDate DATE NOT NULL,
videoStatus char(1) DEFAULT 'X',
videoCategory varchar2(15) NOT NULL,
regNo number(6) NOT NULL,
AdminId number(9),
commentId number(9),
CONSTRAINT pk_videoId PRIMARY KEY (videoId),
CONSTRAINT fk_r_regNo FOREIGN KEY (regNo) REFERENCES EducateYou_Member,
CONSTRAINT fk_p_AdminId FOREIGN KEY (AdminId) REFERENCES EducateYou_Admin,
CONSTRAINT fk_n_commentId FOREIGN KEY (commentId) REFERENCES EducateYou_Comment
);
create table EducateYou_VideoRating(
rating number(2) NOT NULL,
regNo number(9),
videoId number(9),
CONSTRAINT pk_video_rating PRIMARY KEY (videoId, regNo),
CONSTRAINT fk_x_videoId FOREIGN KEY (videoId) REFERENCES EducateYou_Video,
CONSTRAINT fk_z_regNo FOREIGN KEY (regNo) REFERENCES EducateYou_Member
);
create table EducateYou_Admin
(
AdminId number(9),
firstName varchar2(15),
surname varchar2(15),
adminActions varchar2(40),
CONSTRAINT pk_AdminId PRIMARY KEY (AdminId)
);
create table EducateYou_Group(
groupID number(5) NOT NULL,
groupname varchar2(15) NOT NULL,
regNo number(6) NOT NULL,
CONSTRAINT pk_groupID PRIMARY KEY (groupID),
CONSTRAINT fk_i_regNo FOREIGN KEY (regNo) REFERENCES EducateYou_Member
);
create table EducateYou_Comment(
commentId number(9),
commentStatus char(1) DEFAULT 'A',
commentTime timestamp,
counter number(5) DEFAULT 5,
educateYouComment varchar2(50),
regNo number(6) NOT NULL,
CONSTRAINT pk_commentId PRIMARY KEY (commentId),
CONSTRAINT fk_b_regNo FOREIGN KEY (regNo) REFERENCES EducateYou_Member
);
create table EducateYou_FollowList(
followListID number(9),
regNo number(9),
CONSTRAINT pk_followListID PRIMARY KEY (followListID),
CONSTRAINT fk_z_regNo FOREIGN KEY (regNo) REFERENCES EducateYou_Member
);
create table Violation_Type
(
violation_TypeId varchar2(9),
violationId number(9),
CONSTRAINT pk_violation_TypeId PRIMARY KEY (violation_TypeId, violationId ),
CONSTRAINT fk_m_violationId FOREIGN KEY (violationId) REFERENCES EducateYou_Violation
);
create table EducateYou_Member
(
regNo number(6),
status char(1) DEFAULT 'A',
collegeId varchar2(9) NOT NULL,
CONSTRAINT pk_regNo PRIMARY KEY (regNo),
CONSTRAINT fk_l_collegeId FOREIGN KEY (collegeId) REFERENCES Registered_Student
);
create table Registered_Student
(
collegeId varchar2(9),
password varchar2(9) NOT NULL,
firstname varchar2(20) NOT NULL,
surname varchar2(20) NOT NULL,
dob date NOT NULL,
street varchar2(25) NOT NULL,
town varchar2(10) NOT NULL,
county varchar2(15) NOT NULL,
college varchar2(30) NOT NULL,
course varchar2(10) NOT NULL,
CONSTRAINT pk_collegeId PRIMARY KEY (collegeId)
);
Drop Table Syntax
Add SET FOREIGN_KEY_CHECKS = 0; in beginning to ignore the foreign key constraints while deleting the tables and use a single Drop command for all tables as once with CASCADE Option as below:
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS Registered_Student,
IF EXISTS EducateYou_VideoRating,
IF EXISTS EducateYou_Video,
IF EXISTSEducateYou_Violation,
IF EXISTS EducateYou_Member,
IF EXISTS Violation_Type,
IF EXISTS EducateYou_Comment,
IF EXISTS EducateYou_FollowList,
IF EXISTS EducateYou_Group,
IF EXISTS EducateYou_Admin
CASCADE;
Alternatively, drop all the constraints first and then drop the tables.