Below is my table-
create table employee1(
fname varchar(15) not null,
minit char(15) ,
lname varchar(15) not null,
ssn char(9) not null,
bdate date,
address varchar(30),
sex char,
salary decimal(10,2),
superssn char(9),
dno int not null default 1,
constraint emppk
primary key (ssn),
constraint empsupkerfk
foreign key (superssn) references employee1(ssn) on delete set null on update cascade,
constraint empdeptfk
foreign key (dno) references department(dnumber) on delete set default on update cascade
);
Here is my insert statment-
insert into employee1
(
fname,minit,lname,ssn,bdate,address,sex,salary,superssn,dno
)
values (
'jhon','b','smith','123456789','1955-01-09','731 fondren,houston, tx','m','30000','33344555','5'
)
This is the error what I am getting-
Error Code: 1452. Cannot add or update a child row: a foreign key
constraint fails (employee.employee, CONSTRAINT employee_ibfk_1
FOREIGN KEY (superssn) REFERENCES employee (ssn)
The error is quite clear and it means that you are trying to insert into employee1 a superssn value that does not exist in employee.
From the docs:
Foreign key relationships involve a parent table that holds the
central data values, and a child table with identical values pointing
back to its parent. The FOREIGN KEY clause is specified in the child
table.
It will reject any INSERT or UPDATE operation that attempts to create
a foreign key value in a child table if there is no a matching
candidate key value in the parent table.
Related
I am doing on these two tables, which is accountinfo and userrecipeinfo
accountinfo
create table accountinfo
(
id int NOT NULL AUTO_INCREMENT,
username varchar(80),
password varchar(80),
name varchar(80),
primary key (id)
);
userrecipeinfo
create table userrecipeinfo
(
recipeid int NOT NULL AUTO_INCREMENT,
recipename varchar(80),
reciperating int,
recipephoto LONGTEXT,
primary key (recipeid),
foreign key (recipeid) references accountinfo(id)
);
However, when I try to insert one of the values
insert into userrecipeinfo (recipename, reciperating, recipephoto)
values ('tom yum', 4, 'https://www.cbronline.com/wp-content/uploads/2016/07/Trolling.jpg');
I get an error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (userinfo.userrecipeinfo, CONSTRAINT userrecipeinfo_ibfk_1 FOREIGN KEY (recipeid) REFERENCES accountinfo (id))
I would like to know what caused this error. Thanks!
You are violating the foreign key constraint. When a foreign key is added it must match a existing value in the reference table.
In your case userrecipeinfo.recipeid refers to accountinfo.id, so when you insert a row into userrecipeinfo, there must be a corresponding row in accountinfo which matches accountinfo.id = userrecipeinfo.recipeid.
You can try select * from accountinfo where id=4; to see whether there is a row whose id is 4.
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!
I'am trying to add foreign key from department table to employee table. First one is done, But I can't create department table, it pops up error
ERROR 1005 (HY000): Can't create table `assignment`.`department` (errno: 150 "Foreign key constraint is incorrectly formed")
Like this.
CREATE TABLE employee
(
First_Name VARCHAR(15) NOT NULL,
Mid_Name CHAR,
Last_Name VARCHAR(15) NOT NULL,
SSN_Number CHAR(9) PRIMARY KEY NOT NULL,
Birthday DATE,
Address VARCHAR(50),
Sex CHAR CHECK(Sex='M' OR Sex='F' OR Sex='m' OR Sex='f'),
Salary Decimal(10,2) DEFAULT'800',
Supervisor_SSN CHAR(9),
Department_Number INT,
CONSTRAINT fk_employee FOREIGN KEY(Supervisor_SSN)
REFERENCES employee(SSN_Number) ON DELETE SET NULL
);
CREATE TABLE department
(
Department_Name VARCHAR(15) NOT NULL UNIQUE,
Department_Number INT PRIMARY KEY NOT NULL,
Manaager_SSN CHAR(9) NOT NULL,
Manager_Start_Date Date,
CONSTRAINT fk_manager FOREIGN KEY(Manaager_SSN)
REFERENCES employee(SSN_Number) ON DELETE SET NULL
);
I expect to add foreign key on Manaager_SSN to SSN_Number in employee table.
The option ON DELETE SET NULL is not valid if the column is declared NOT NULL. You're telling it to set the column to an impossible value.
So either change the declaration of Manaager_SSN to NULL, or change the foreign key to ON DELETE CASCADE. The former is probably more appropriate -- if the manager of a department leaves the company, you don't usually dissolve the department.
The foreign key definition includes
... ON DELETE SET NULL
^^^^^^^^
but the foreign key column is defined as non-NULL
Manaager_SSN CHAR(9) NOT NULL,
^^^^^^^^
SOLVED! Answered in separate post below
"Cannot add foreign key constraint"
This occurs ONLY when in table Consist_of I use the code:
INDEX trade_name (trade_name),
FOREIGN KEY (trade_name)
REFERENCES Drug(trade_name)
ON DELETE CASCADE,
PRIMARY KEY (pre_no, dssn, pname, trade_name)
If I take out trade_name from PRIMARY KEY () and remove the INDEX to CASCADE, code, then my stuff successfully compiles. All I'm trying to do is have it so I can enter in Drugs with the same name, and have the unique key be the combination of pname and trade_name
all code:
CREATE TABLE Doctor (
dssn INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
dname VARCHAR(30),
specialty VARCHAR(30)
);
CREATE TABLE Prescription (
pre_no INT(6) UNSIGNED PRIMARY KEY,
dssn INT(6) UNSIGNED,
INDEX dssn (dssn),
FOREIGN KEY (dssn)
REFERENCES Doctor(dssn)
ON DELETE CASCADE,
pdate DATETIME
);
CREATE Table Ph_company (
pname varchar(30) PRIMARY KEY,
phone varchar(12)
);
CREATE Table Drug (
pname varchar(30),
trade_name VARCHAR(30),
formula VARCHAR(30),
INDEX pname (pname),
FOREIGN KEY (pname)
REFERENCES Ph_company(pname)
ON DELETE CASCADE,
key(pname, trade_name)
);
CREATE Table Consist_of (
pre_no INT(6) UNSIGNED,
dssn INT(6) UNSIGNED,
pname varchar(30),
trade_name VARCHAR(30),
INDEX pre_no (pre_no),
FOREIGN KEY (pre_no)
REFERENCES Prescription(pre_no)
ON DELETE CASCADE,
INDEX dssn (dssn),
FOREIGN KEY (dssn)
REFERENCES Prescription(dssn)
ON DELETE CASCADE,
INDEX pname (pname),
FOREIGN KEY (pname)
REFERENCES Drug(pname)
ON DELETE CASCADE,
INDEX trade_name (trade_name),
FOREIGN KEY (trade_name)
REFERENCES Drug(trade_name)
ON DELETE CASCADE,
PRIMARY KEY (pre_no, dssn, pname, trade_name)
);
Since the primary key in DRUG is a composite key consisting of 2 fields, you must set up the foreign key the same way. So instead of declaring 2 foreign keys (1 for pname and another for trade_name), do this instead:
FOREIGN KEY ('pname','trade_name')
REFERENCES Drug('pname','trade_name')
Figures that after 2 hours of head-banging, I figure out the solution (I think) 2 minutes after I ask you guys here.
I added
INDEX trade_name (trade_name),
key(pname, trade_name)
to the end of Drug's creation code, and it works now, allowing me to enter in duplicate drug names.
I am trying to add records into two tables below,
CREATE TABLE customer
(Custno CHAR(3),
Custname VARCHAR(25) NOT NULL,
Custstreet VARCHAR(30) NOT NULL,
Custcity VARCHAR(15) NOT NULL,
Custprov VARCHAR(3) NOT NULL,
Custpcode VARCHAR(6) NOT NULL,
Disc DECIMAL(3,1),
Balance DECIMAL(7,2),
Credlimit DECIMAL(5),
Srepno CHAR(3),
CONSTRAINT pkcustno PRIMARY KEY (Custno),
CONSTRAINT fksrepno FOREIGN KEY (Srepno) REFERENCES salesrep(Srepno)
);
CREATE TABLE orders
(Orderno CHAR(5) UNIQUE NOT NULL,
Orderdate DATE,
Custno CHAR(3) NOT NULL,
CONSTRAINT fkordercust FOREIGN KEY (Custno) REFERENCES customer (Custno)
);
When adding like this,
INSERT INTO orders(Orderno, Orderdate, Custno) VALUES('14587','2011-11-09', '125' );
INSERT INTO orders(Orderno, Orderdate, Custno) VALUES('11547','2011-11-07', '125' );
I get, "Cannot add or update a child row: a foreign key constraint fails (sh.orders, CONSTRAINT fkordercust FOREIGN KEY (Custno) REFERENCES customer (Custno))
"
Is something wrong the table?
You do not have a customer with CustNo = '125'. Because of this, the Foreign key fails. You are trying to place an order for a non-existent customer, the DB throws an error.
Do you actually have a customer row for customer number 125? I think not. The error message is telling you exactly what's wrong.
The foreign key constraint which ensures that no orders can be created for non-existent customers is being violated:
CONSTRAINT fkordercust FOREIGN KEY (Custno) REFERENCES customer (Custno)
Create the customer row first then you can add order rows for that customer to your heart's content.
Your table is fine, you just don't have a customer with a CustNo of '125' in the database.
You have created a foreign key to the customer table, but ( apparently ) inserted no data into it.
Do you have a customer with a number of 125?