In the given Images, There are two tables. In the table STUD_MEMBER, Dept_ID is a foreign key which is referring to Dept_ID in table DEPARTMENT.:
So when I add foreign key constraints in mysql at phpmyadmin like
CREATE TABLE DEPARTMENT(
Dept_ID INT,
Dept_Name VARCHAR(25));
INSERT INTO DEPARTMENT VALUES(1,"Information Technology");
INSERT INTO DEPARTMENT VALUES(2,"Electrical");
INSERT INTO DEPARTMENT VALUES(3,"Civil");
INSERT INTO DEPARTMENT VALUES(4,"Mechanical");
INSERT INTO DEPARTMENT VALUES(5,"Chemical");
CREATE TABLE STUD_MEMBER(
Roll_No INT NOT NULL PRIMARY KEY,
FName VARCHAR(20),
MName VARCHAR(20),
SName VARCHAR(20),
Dept_ID INT,
FOREIGN KEY (Dept_ID) REFERENCES DEPARTMENT(Dept_ID),
Semester INT,
Contact_No INT,
Gender VARCHAR(6));
It is showing an error that 1215- cannot add foreign key constraint. As far as I know, it is the correct way to add a foreign key, I am so confused why it is wrong. Please help in solving this.
It looks like the referenced column has to be either a primary key, or it has to have a unique index. The following CREATE TABLE statement worked for me:
CREATE TABLE DEPARTMENT (
Dept_ID INT PRIMARY KEY NOT NULL,
Dept_Name VARCHAR(25)
);
if you are defining foreign key in child, the parent field must have an index defined on it.
check reference from HERE
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
Related
I try to create a table for the company database.
As I tried to add some foreign keys in there, something goes wrong.
CREATE TABLE employee (
emp_id INT PRIMARY KEY,
first_name VARCHAR(40),
last_name VARCHAR(40),
birth_day DATE,
sex VARCHAR(1),
salary INT,
super_id INT,
branch_id INT unique
);
CREATE TABLE branch (
branch_id INT PRIMARY KEY,
branch_name VARCHAR(40),
mgr_id INT,
mgr_start_date DATE,
FOREIGN KEY(mgr_id) REFERENCES employee(emp_id) ON DELETE SET NULL
);
ALTER TABLE employee
ADD FOREIGN KEY(branch_id)
REFERENCES branch(branch_id)
ON DELETE SET NULL;
ALTER TABLE employee
ADD FOREIGN KEY(super_id)
REFERENCES employee(emp_id)
ON DELETE SET NULL
The "alter table employee" part to add foreign key (branch) failed with the following statement.
ER_FK_NO_INDEX_PARENT: Failed to add the foreign key constraint. Missing index for constraint 'employee_ibfk_10' in the referenced table 'branch'
Could this be some problem with my setting?
I have created two tables (emp and dept). Emp contains a foreign key (deptid). I am attempting to delete a row from the dept table and am receiving a foreign key constraint error. I then altered the emp table foreign key to add constraint and delete on cascade. The code is copied here
create table dept (
deptid int primary key,
deptname varchar(20),
locid int);
create table emp (
empid int primary key,
frname varchar(15),
lname varchar(20),
hiredate datetime,
deptid int,
foreign key (deptid) references dept(deptid));
alter table emp add constraint fk_deptid foreign key (deptid)
references dept(deptid) on delete cascade;
This is the error message that I receive:
Query Error: Error: ER_ROW_IS_REFERENCED_2: Cannot delete or update a parent row: a foreign key constraint fails (test.emp, CONSTRAINT emp_ibfk_1 FOREIGN KEY (deptid) REFERENCES dept (deptid))
The problem is that you are creating two foreign key constraints for the same column. Avoid doing this, it's confusing.
The first one is created while you create the table and is unnamed. Since you didn't provide a name for it, MySQL automatically names it for you as emp_ibfk_1. This one does not have CASCADE DELETE and prevents deletion of parent keys.
The second one is on a separate SQL statement and you name it fk_deptid. This one has CASCADE DELETE and allows deletion of parent keys.
While enforcing the foreign key constraints MySQL cannot delete the row since the first constraint does not allow it. That's the error you are getting.
This is a confusing situation and I would avoid doing something like this. I would suggest having a single FK constraint for the column; specifically I would remove the first one.
For example:
create table dept (
deptid int primary key,
deptname varchar(20),
locid int);
create table emp (
empid int primary key,
frname varchar(15),
lname varchar(20),
hiredate datetime,
deptid int
-- , foreign key (deptid) references dept(deptid) -- removed
);
alter table emp add constraint fk_deptid foreign key (deptid)
references dept(deptid) on delete cascade;
insert into dept (deptid, deptname, locid)
values (1, 'Math', 123);
insert into emp (empid, frname, lname, hiredate, deptid)
values (10, 'Peter', 'Fonda', null, 1);
delete from dept where deptid = 1; -- works!
This is my sql code, and everytime I execute it on command, it is giving me an error, can anyone tell me what am I missing here? It is giving me
"Foreign key constraint is incorrectly formed" error. Any help would be awesome.
Create table course (course_id varchar(8), title varchar(50), dept_name varchar(20), credits numeric(2,0) check (credits > 0), primary key (course_id), foreign key (dept_name) references department on delete set null );
This is the reference table:
create table department
(dept_name varchar(20),
building varchar(15),
budget numeric(12,2) check (budget > 0),
primary key (dept_name)
);
See documentation:
Foreign Keys
...
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
...
Example:
create table if not exists course (
course_id varchar(8),
title varchar(50),
dept_name varchar(20),
credits numeric(2,0) check (credits > 0),
primary key (course_id),
foreign key (dept_name)
-- references department on delete set null
references department (dept_name) on delete set null
);
See dbfiddle.
I have an error code which is Error Code: 1215. Cannot add foreign key constraint in MySQL. My code is
DROP TABLE IF EXISTS Formed;
DROP TABLE IF EXISTS Album;
DROP TABLE IF EXISTS Band;
DROP TABLE IF EXISTS Customers;
DROP TABLE IF EXISTS Track;
CREATE TABLE Formed(
FormedID int NOT NULL,
YearFormed int,
CountryFormed varchar(50),
CityFormed varchar(50),
BandMembers varchar(400),
PRIMARY KEY(FormedID))
ENGINE=InnoDB;
CREATE TABLE Track (
TrackID int NOT NULL,
AlbumID int NOT NULL,
Songs varchar (100),
TrackNumber varchar (20),
Title varchar (20),
TrackDuration varchar (4),
PRIMARY KEY (TrackID),
FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE)
ENGINE=InnoDB;
CREATE TABLE Album(
AlbumID int NOT NULL,
TrackID int NOT NULL,
BandID int NOT NULL,
Price varchar(5),
PublicationDate varchar(11),
Title varchar(30),
Genre varchar (36),
PRIMARY KEY(AlbumID),
FOREIGN KEY (TrackID) REFERENCES Track(TrackID)ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY (BandID) REFERENCES Band(BandID)ON DELETE SET NULL ON UPDATE CASCADE)
ENGINE=InnoDB;
CREATE TABLE Band(
BandID int NOT NULL,
AlbumID int NOT NULL,
RecordLabel varchar(50),
PRIMARY KEY(BandID),
FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE)
ENGINE=InnoDB;
CREATE TABLE Customers (
CustomerID int NOT NULL,
CName varchar (20),
CPhone int (11),
CEmail varchar (50),
CPPaid varchar (50),
CPDate date,
PRIMARY KEY (CustomerID))
ENGINE=InnoDB;
It creates the first table named Formed, but it's giving me the error when it tries and creates the second table and I don't know why. I know a bit about MySQL and I'm teaching myself about Foreign Keys. I have had a look online on why I could be getting this error but couldn't find anything useful.
From the error message, it seems like you are trying to create Track table before Album table and hence, it's failing as it is not able to find parent table (and column) for foreign key constraint.
I would suggest creating the tables with Primary keys only and then, apply foreign key constraints once all 3 tables are created, e.g.:
ALTER TABLE `Track`
ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE);
As a rule All reference fields in child tables MUST HAVE index defined on them as like in parent table. They must also follow some other constraints.
As per documentation on foreign key constraints:
REFERENCES parent_tbl_name (index_col_name,...)
Define an INDEX on relevant child columns. And make sure that child column definitions must match with those of their parent column definitions.
Code change suggested:
CREATE TABLE Formed( ... ) -- no change suggested
CREATE TABLE Customers ( ... ) -- no change suggested
CREATE TABLE Band(
...
AlbumID int NOT NULL,
...
KEY (AlbumID), -- <---- add this line
...
);
CREATE TABLE Album(
...
TrackID int NOT NULL,
BandID int NOT NULL,
...
KEY (TrakID), -- <---- add this line
KEY (BandID), -- <---- add this line
...
-- FOREIGN KEY (TrackID) -- <-- add this using ALTER
-- REFERENCES Track(TrackID) -- after creating
-- ON DELETE SET NULL ON UPDATE CASCADE, -- Track table
);
ALTER TABLE Band ADD
FOREIGN KEY ( AlbumID )
REFERENCES Album( AlbumID )
ON DELETE SET NULL ON UPDATE CASCADE;
CREATE TABLE Track ( ... ) -- no changes suggested
ALTER TABLE Album ADD
FOREIGN KEY ( TrackID )
REFERENCES Track( TrackID );
ON DELETE SET NULL ON UPDATE CASCADE;
Refer to:
MySQL Using FOREIGN KEY Constraints
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION
I am new to databases and I keep getting an error when I try to create these tables. Where is a mistake?
I have found loads of questions similar to mine, but they didn't help me to resolve this problem.
CREATE TABLE IF NOT EXISTS course
(
cou_id VARCHAR(3),
course_name VARCHAR(25),
CONSTRAINT pk_course PRIMARY KEY (cou_id, course_name)
);
CREATE TABLE IF NOT EXISTS students_marks
(
stu_id INT,
student_name VARCHAR(25),
course_name VARCHAR(25),
first_mark NUMERIC(2,0),
second_mark NUMERIC(2,0),
third_mark NUMERIC(2,0),
CONSTRAINT pk_studentsmarks PRIMARY KEY (stu_id),
CONSTRAINT fk_studentsmarks_course FOREIGN KEY (course_name) REFERENCES course (course_name)
);
This is from INNODB STATUS.
LATEST FOREIGN KEY ERROR
------------------------
130603 20:17:22 Error in foreign key constraint of table testdb/students_marks:
FOREIGN KEY (course_name) REFERENCES course (course_name)
):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Your primary key is set to cou_id and course_name in your course table. To add a foreign key constraint in your students_marks table, you'd have to reference both fields (and include both fields in your table definition):
CREATE TABLE IF NOT EXISTS course
(
cou_id VARCHAR(3),
course_name VARCHAR(25),
CONSTRAINT pk_course PRIMARY KEY (cou_id, course_name)
);
CREATE TABLE IF NOT EXISTS students_marks
(
stu_id INT,
student_name VARCHAR(25),
cou_id VARCHAR(3),
course_name VARCHAR(25),
first_mark NUMERIC(2,0),
second_mark NUMERIC(2,0),
third_mark NUMERIC(2,0),
CONSTRAINT pk_studentsmarks PRIMARY KEY (stu_id),
CONSTRAINT fk_studentsmarks_course FOREIGN KEY (cou_id,course_name) REFERENCES course(cou_id,course_name)
);
SQL Fiddle Demo
You are referencing only one field of a composed primary key!