Cannot add foreign key in MySQL? - mysql

Here is the statement I am executing and related error, any hints what is wrong and how to debug further is appreciated. Using MySQL Workbench/MySQL.
Especially confused what means child row here? How foreign key related to child row? And what is the child row here?
ALTER TABLE Orders
ADD CONSTRAINT fk_Customer FOREIGN KEY (CustomerID)
REFERENCES Customers(CustomerID)
Error Code: 1452. Cannot add or update a child row: a foreign key
constraint fails (test.#sql-ff_2, CONSTRAINT fk_Customer FOREIGN
KEY (CustomerID) REFERENCES Customers (CustomerID))

This error means that your tables contain data that should not be allowed by the foreign key you're trying to create. You could use a query to find them:
SELECT *
FROM orders
WHERE customerid NOT IN (SELECT customerid FROM customers)
If you're sure these rows are indeed faulty, you could use a similar delete statement to remove them:
DELETE FROM orders
WHERE customerid NOT IN (SELECT customerid FROM customers)

Related

#1452 - Cannot add or update a child row: a foreign key constraint fails on my table

I Have 2 tables which is departements and students with this schema on my foreign key
departements.id = students.departement_id
i tried to delete one of my departement.id but it returns an error with this
#1452 - Cannot add or update a child row: a foreign key constraint fails (`u1556075_sia_uiii2`.`#sql-f847_33d3d1a`, CONSTRAINT `departements_fk2` FOREIGN KEY (`id`) REFERENCES `students` (`departement_id`)
honestly idk what makes this happen because my foreign key on student is just like this
ALTER TABLE `students` ADD CONSTRAINT `students_fk2` FOREIGN KEY (`departement_id`) REFERENCES `departements`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT;
You can't delete a row in departments if there is one or more rows in students referencing that row's department id. The reason is that if you were to delete the row in departments, then some rows in students would reference a department id that no longer exists in the database, which would be a violation of the foreign key constraint.
You must first UPDATE the students table to change the department id on rows that match the department you want to delete. Either change those students to some other department, or else set the department_id to NULL. Or I suppose it would also work to delete the rows in students, but I assume you don't want to do that.

Two columns in same table and same foreign key

I'm developing an application, actually a billing system. Here accountant can add invoice for a client.
I have two tables, users and invoices:
invoices (user_id, created_by)
users (id)
Invoices has two columns, user_id and created_by, I want both to be linked with id of the users table.
Already user_id has been added as foreign key. Now I'm trying to add created_by as foreign key. So issued following command:
ALTER TABLE `invoices`
ADD FOREIGN KEY (`created_by`) REFERENCES `secureap_maind`.`users` (`id`)
ON DELETE RESTRICT ON UPDATE RESTRICT;
And I'm getting an error message.
#1452 - Cannot add or update a child row: a foreign key constraint fails (secureap_maind.#sql-3717_a323d, CONSTRAINT #sql-3717_a323d_ibfk_2 FOREIGN KEY (created_by) REFERENCES users (id))
I'm not sure if I can add two columns as foreign key. IF possible, can you please advice to do that?
Thanks in advance.
This SO post implies that removing your ON DELETE RESTRICT clause from the ALTER TABLE statement might solve your problem. Try running this query instead:
ALTER TABLE `invoices`
ADD FOREIGN KEY (`created_by`) REFERENCES `secureap_maind`.`users`(`id`)
I am assuming that the invoices table was created using InnoDB rather than MyISAM, the latter which does not enforce foreign keys.

MySQL: Alter table to set Foreign key

Although there are some similar questions about the subject, I can't find the right answer for my problem. I have 2 tables called customer and car. What I want to do is this: When I delete a customer from database, I want the car that belongs to that customer will be automatically deleted as well. The code that MySQL Workbench generated for me is this:
ALTER TABLE `autocare`.`car`
ADD CONSTRAINT `customerId`
FOREIGN KEY (`CUSTOMER_ID`)
REFERENCES `autocare`.`customer` (`ID`)
ON DELETE CASCADE
ON UPDATE RESTRICT;
And I get this error:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
(`autocare`.`#sql-80c_388`, CONSTRAINT `customerId` FOREIGN KEY (`CUSTOMER_ID`)
REFERENCES `customer` (`ID`) ON DELETE CASCADE)
There was no relation between those tables before. Any ideas? Thanks in advance!
Your goal is ultimately to implement a cascading deletion from customer to car. When you attempt to add the constraint with the tables as they are now, it fails because the car table must include rows having a a CUSTOMER_ID value which does not currently exist in the parent customer table.
You should first locate those orphan rows and delete them (since your goal is to delete them anyway). You can find them with a query like:
SELECT *
FROM car
WHERE
CUSTOMER_ID NOT IN (SELECT ID FROM customer)
Once the orphan records are removed, the foreign key constraint can be met by the remaining existing rows and your ALTER TABLE statement will succeed.

MySQL Error Code: 1452 when adding index and foreign key constraints to an existing table

I have a MySQL database with an existing (and not removable) cities table with a new reference to a table province by a field province_id.
When I run:
ALTER TABLE cities ADD province_id INTEGER NOT NULL;
ALTER TABLE cities ADD INDEX (province_id),
ADD FOREIGN KEY (province_id) REFERENCES provinces (id);
I got next error on the second query, adding the index and foreign key:
ALTER TABLE cities ADD INDEX (province_id), ADD FOREIGN KEY (province_id) REFERENCES provinces (id) Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`yanpytest`.`#sql-16d8_325`, CONSTRAINT `#sql-16d8_325_ibfk_3` FOREIGN KEY (`province_id`) REFERENCES `provinces` (`id`))
I donĀ“t understand why, and this is not working in my production environment, in development it worked (both MySQL).
This probably means that in the province_id column in the cities table you have some value(s) e.g. 123 which does not exist in the provinces table in the id column there. So the foreign key (FK) constraint cannot be enforced by MySQL and it fails on you.
You can find the violating records by running:
SELECT * FROM `cities` WHERE `province_id` NOT IN
(SELECT id FROM `provinces`)

error adding a foreign key constraint

I have the following query:
ALTER TABLE ROUTE ADD FOREIGN KEY (RID) REFERENCES RESERVATION(RID) ON DELETE CASCADE
but it generates me an error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`SmarTrek`.`#sql-91e_d09`, CONSTRAINT `FK_RID` FOREIGN KEY (`RID`) REFERENCES `RESERVATION` (`RID`) ON DELETE CASCADE)
In designer mode, here's what it looks like:
That would meant that you already have data in the ROUTE table that does not satisfy the foreign key constraint.
To find the offending records, so you can update them to some other value (that exists), you can use
select *
from route
where rid not in (select rid from reservation)
THERE may b 2 reasons
there may b some row in ROUTE TABLE which have RID that does not exist in RESERVATION(RID)
or check the DATATYPE OF ROUTE (RID) & RESERVATION(RID) both should be same ( unsigned/signed)