Cannot add or update child row MySQL Error 1452 - mysql

I am getting this error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (university.registration, CONSTRAINT registration_ibfk_2 FOREIGN KEY (section_id) REFERENCES Section (section_id))
This is my code
INSERT INTO Registration VALUES (24766, 1102, 'B', 'B');
CREATE TABLE Registration (
student_id INT,
section_id INT,
midterm_grade VARCHAR(5),
final_grade VARCHAR(5),
PRIMARY KEY (student_id, section_id),
FOREIGN KEY (student_id)
REFERENCES Student (student_id),
FOREIGN KEY (section_id)
REFERENCES Section (section_id)
);
Any help would be appreciated on fixing this problem.

This is a common error in MySQL, most likey caused by either that student_id 24766 does not exist in the Student table, or section_id 1102 does not exist in the Section table.
The fix is to simply make sure that your foreign keys in the Registration table point to actual primary keys of records in the other two tables. So, you may need to insert some data to resolve this error.

Related

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails, Can anybody assist

I was wondering if anybody would be so kind as to try help me figure out th problem with my code. I have an extremially limited knowledge of sql I am a student and this is my first year doing sql.
Here is the first table containing the model as the primary key.
create table Train(
Model int primary key auto_increment,
fullname varchar(40),
OriginStation varchar(80),
destination varchar (80),
TrainNo varchar (15),
PassengerCode varchar (20) not null,
TrackID int,
foreign key (TrackID) references Tracks(TrackID) on update cascade on delete cascade
);
Then I have used this as a foreign key in a few other tables and had no issues, but when I tried to use it as a foreign key inside this table this is where the issue occurs.
create table Trainseats(
seatno int primary key auto_increment,
Model int,
PassengerCode int,
foreign key (Model) references Train(Model) on update cascade on delete cascade,
foreign key (PassengerCode) references Passenger(PassengerCode) on update cascade on delete cascade
);
This is the error Im facing.
12:09:39 insert into Trainseats values( 530, 2000, 100 ) Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (railway.trainseats, CONSTRAINT trainseats_ibfk_2 FOREIGN KEY (PassengerCode) REFERENCES passenger (PassengerCode) ON DELETE CASCADE ON UPDATE CASCADE) 0.016 sec
If anybody could shine a light on this issue it would be much appreciated.
This is your code:
insert into Trainseats
values( 530, 2000, 100 );
You have left out the columns! So it is interpreted as:
insert into Trainseats (seatno, Model, PassengerCode)
values( 530, 2000, 100 );
The error is saying that PassengerCode = 100 does not exist in the Passenger table.
Note: Normally, you do not insert into auto increment columns. And you should always explicitly list the columns:
insert into Trainseats (Model, PassengerCode)
values( 2000, 100 );

ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint problem in SQL [duplicate]

This question already has an answer here:
Failed to add the foreign key constraint. Missing index for constraint Error Code: 1822
(1 answer)
Closed 2 years ago.
I was creating a database by creating 3 tables (classes, lectures, taking), and then altering the table in order add the foreign key.
However, I keep getting the following error:
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint
I don't seem to find any problem with the codes so what could be the problem??
(I was using mySQL Workbench. I tried copying and pasting as a txt file because I though it might be a collation problem, but still the same problem would occur)
The code is as follows:
CREATE TABLE classes (
course_id VARCHAR(8),
classes_id VARCHAR(10),
semester VARCHAR(10),
year VARCHAR(10),
PRIMARY KEY (course_id, classes_id, semester, year)
);
CREATE TABLE taking (
student_id VARCHAR(8),
course_id VARCHAR(10),
classes_id VARCHAR(10),
semester VARCHAR(10),
year VARCHAR(10),
grade char(1),
PRIMARY KEY (student_id, course_id, semester, year)
);
CREATE TABLE lectures (
professor_id VARCHAR(8),
course_id VARCHAR(10),
classes_id VARCHAR(10),
semester VARCHAR(10),
year VARCHAR(10),
PRIMARY KEY (professor_id, course_id, semester, year)
);
ALTER TABLE taking ADD CONSTRAINT consTAKE3 FOREIGN KEY(classes_id) REFERENCES classes(classes_id) ON DELETE CASCADE;
ALTER TABLE taking ADD CONSTRAINT consTAKE4 FOREIGN KEY(semester) REFERENCES classes(semester) ON DELETE CASCADE;
ALTER TABLE taking ADD CONSTRAINT consTAKE5 FOREIGN KEY(year) REFERENCES classes(year) ON DELETE CASCADE;
ALTER TABLE lectures ADD CONSTRAINT consLEC3 FOREIGN KEY(classes_id) REFERENCES classes(classes_id) ON DELETE CASCADE;
ALTER TABLE lectures ADD CONSTRAINT consLEC4 FOREIGN KEY(semester) REFERENCES classes(semester) ON DELETE CASCADE;
ALTER TABLE lectures ADD CONSTRAINT consLEC5 FOREIGN KEY(year) REFERENCES classes(year) ON DELETE CASCADE;
The Error would be as follows:
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'consTAKE3' in the referenced table 'classes'
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'consTAKE4' in the referenced table 'classes'
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'consTAKE5' in the referenced table 'classes'
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'consLEC3' in the referenced table 'classes'
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'consLEC4' in the referenced table 'classes'
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'consLEC5' in the referenced table 'classes'
Right now, I'm trying to execute this from the cmd using ysql –u root –p. Still, the same problem is occurring.
Since you have a composite primary key in all tables, so all references must also include all the composite key columns in the table to map properly.
Unless you have a unique constraint/index on the composite primary key columns on each table.
To create relation in the tables, try this for dbo.taking, follow the similar approach for other tables too
ALTER TABLE dbo.taking
ADD CONSTRAINT FK_taking_classes
FOREIGN KEY(course_id, classes_id, semester, year) REFERENCES classes(course_id,
classes_id, semester, year)
The character length of course_id in both the table differ, which results in not creating FK . Please set it to varchar(8) in taking table same of classes. It will definitely solve the problem. I have created the tables and also have FKs by using the provided query.
Then follow the above mentioned Query:
Since you have a composite primary key in all tables, so all
references must also include all the composite key columns in the
table to map properly.
Unless you have a unique constraint/index on the composite primary key
columns on each table.
To create relation in the tables, try this for dbo.taking, follow
the similar approach for other tables too
ALTER TABLE dbo.taking
ADD CONSTRAINT FK_taking_classes
FOREIGN KEY(course_id, classes_id, semester, year) REFERENCES classes(course_id,
classes_id, semester, year)

Problem with the fk and pk which are in the same table and related

"HProblem with the fk and pk which are in the same table and related."
So, i want to insert in table 'employee' values but the program show me error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (ikbo_6.employee, CONSTRAINT employee_ibfk_1 FOREIGN KEY (manager_id) REFERENCES employee (employee_id)).
insert into employee values
(1,'Mccain', 'Jhonny','D',1001,101,'2008-05-12',2000.90,100.45,801);
I tried first to add the data to pk_key and only then to the other columns, but this did not work.
insert into employee (last_name,first_name,middle_initial,manager_id,job_id,hire_date, salary, commission, department_id) values
('Mccain', 'Jhonny','D',1001,101,'2008-05-12',2000.90,100.45,801);
what am I doing wrong?
The struture employee_id int(6) not null auto_increment primary key,manager_id int(6)
and foreign key (manager_id) references Employee (employee_id)
relation key

MySql - Cannot add or update a child foreign key constraint fails [duplicate]

This question already has answers here:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
(28 answers)
Closed 7 years ago.
I have two tables, 'booking' and 'isBooked'. I want to add values to the isBooked table. But i keep getting an error "Cannot add or update a child foreign key constraint fails".
CREATE TABLE booking (
bookingID INT AUTO_INCREMENT,
customerID INT,
startDate DATE,
endDate DATE,
dateBookedOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
employeeID int,
PRIMARY KEY (bookingID),
INDEX idx_start (startDate),
INDEX idx_end (endDate),
FOREIGN KEY (customerID) REFERENCES customer(CustomerID)
);
CREATE TABLE isBooked(
BookingID int,
DogID int,
RunID int,
foreign key (RunID) references Run(RunID),
foreign key (DogID) references Dog(dogID),
foreign key (BookingID) references Booking(BookingID)
);
insert into isbooked values(1, 1, 1);
can anyone tell me why this error appears when trying to insert values to 'isBooked'.
Your isbooked table has foreign key constraints on references to three other tables:
foreign key (RunID) references Run(RunID),
foreign key (DogID) references Dog(dogID),
foreign key (BookingID) references Booking(BookingID)
This constraint makes sure that whatever value you enter, it needs to match one of the rows in referenced tables.
Therefore, the reason you're getting this error is because there is no matching records in one (or maybe all) referenced tables. First you need to add Run, Dog and Booking with IDs you're using in the insert and only then you can add a record to isbooked.

Foreign key reference tableA.column or tableB.column

Is it possible to have a foreign key (InnoDB) reference two possible tables?
If not, is there a workaround for this?
There are two different subjects that contain the same field (interface_id). A third table references this field.
An example being:
physical_interface ( id, name, etc )
virtual_interface ( id, name, etc )
usage ( interface_id, etc )
I had an idea of using a view, but came across this related to SQL server: Can I have a foreign key referencing a column in a view in SQL Server? so it seems you cannot use views in foreign keys.
The alternative, I suppose, would be storing all intefaces in one table but I feel that would be less organized.
Well, the answer is interesting. MySQL 5.6.14, my version, won't stop you from creating a foreign key relationship with 2 tables but that is a bad idea. Let me show you why.
Create 2 master tables: test1 and test3
create table test1 (field1 int, primary key (field1));
create table test3 (field1 int, primary key (field1));
Create a dependent table that will have FK relationship with field1 of both tables.
create table test2 (
field0 int,
field1 int,
constraint fk_test2_test1
foreign key (field1)
references test1 (field1),
constraint fk_test2_test3
foreign key (field1)
references test3 (field1)
);
Great. Now let's add some data and see the issue:
insert into test1 values (1);
insert into test3 values (3);
Master tables are done. Let's add data to dependent table.
insert into test2 values (100, 1);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`test2`, CONSTRAINT `fk_test2_test3` FOREIGN KEY (`field1`) REFERENCES `test3` (`field1`))
insert into test2 values (100, 3);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`test2`, CONSTRAINT `fk_test2_test1` FOREIGN KEY (`field1`) REFERENCES `test1` (`field1`))
insert into test2 values (100, 2);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`test2`, CONSTRAINT `fk_test2_test1` FOREIGN KEY (`field1`) REFERENCES `test1` (`field1`))
So...don't do that.
Proposal
create table interface_type (
id int auto_increment,
type_name varchar(30),
primary key (id)
);
create table interface (
id int auto_increment,
interface_name varchar(30),
interface_type int,
primary key (id),
constraint fk_interface_type
foreign key (interface_type)
references interface_type (id)
);
create table `usage` (
id int auto_increment,
interface_id int,
primary key (id),
constraint fk_usage_interface
foreign key (interface_id)
references interface (id)
);
Now you can add as many types of interfaces in the interface_type table such as:
insert into interface_type (type_name) values ('physical'), ('virtual');
Then, add as many interfaces as you'd like in the interface table, and reference them in the usage table as needed.