MySQL: Alter table to set Foreign key - mysql

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.

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.

error with alter table and foreign key

I have 2 tables :
Installers (Fields: id,company,country,experience,name)
Contacts (Fields: name,phone,address)
I would like to match both names, thereby I could click in one value of the name of Installers and it could show me the values of Contacts table.
However when I am trying to set up the foreign key (my child table will probably be Installers , as I have more tables like that and Contacts would be the parent.) It states this error:
query SQL:
ALTER TABLE `Installers`
ADD FOREIGN KEY (`name`)
REFERENCES `SOLAR_PV`.`Contacts`(`name`)
ON DELETE CASCADE ON UPDATE CASCADE;
MySQL ha dicho: Documentación
1452 - Cannot add or update a child row: a foreign key constraint
fails (SOLAR_PV.#sql-32a_183, CONSTRAINT #sql-32a_183_ibfk_1
FOREIGN KEY (name) REFERENCES Contacts (name) ON DELETE CASCADE
ON UPDATE CASCADE)
Both tables are InnoDB and Contacts.name is indexed as well as Installers.name
Primary Key of Installers is id and Primary Key of Contacs is name.
Any idea about what would be the problem?
It seems your child table contains few records those don't have in master, you can check it by below query-
SELECT id FROM Installers ins
LEFT JOIN SOLAR_PV.Contacts cnt ON ins.name=cnt.name
WHERE cnt.name IS NULL;
Note: Assuming name is int type for better performance as it is primary key in one table.
If you get few records by above query then you can follow below 2 approach-
Approach1: You can either delete these records in child table or insert in master table also and then you can create relationship by this alter command.
Approach2: If you don't want to change in your tables existing data and still want to execute your alter query then use as per below-
SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE `Installers`
ADD FOREIGN KEY (`name`)
REFERENCES `SOLAR_PV`.`Contacts`(`name`)
ON DELETE CASCADE ON UPDATE CASCADE;
SET FOREIGN_KEY_CHECKS=1;

Creating Relationship in MySQL error

I have three tables (all InnoDB with primary keys having int(7) for type)
tblcustomers: primary key is customer_id
tblorders: primary key is order_id (has field for customer_id called order_customer)
tblorder_detail: primary key is order_detail_id (has field for order_id called order_id)
I want a to create a relationship so that deleting a customer deletes their order history.
I used the following statement to alter the Orders table:
ALTER TABLE `tblorders`
ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`order_customer`) REFERENCES `tblcustomers` (`customer_id`) ON DELETE CASCADE ON UPDATE CASCADE;
This was successful and deleting a customer deletes their associated orders.
I then tried the following and I get an error:
ALTER TABLE `tblorder_detail`
ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`order_id`) REFERENCES `tblorders` (`order_id`) ON DELETE CASCADE ON UPDATE CASCADE
This is the error (wtc-ecommerce is the name of the db):
1005 - Can't create table 'wtc-ecommerce.#sql-5d2_c2' (errno: 121)
Reading through other SO posts, seems like everything is correctly configured, so I'm lost.
Thanks

mysql delete and foreign key constraint

I'm deleting selected rows from both table in MYSQL, the two tables have foreign keys.
DELETE d,b
FROM A as b
INNER JOIN B as d on b.bid=d.bid WHERE b.name LIKE '%xxxx%';
MYSQL complains about foreign keys even though I'm trying to delete from both tables:
Error: Cannot delete or update a parent row: a foreign key constraint
fails (`yyy/d`, CONSTRAINT `fk_d_bid` FOREIGN KEY (`bid`) REFERENCES
`b` (`bid`) ON DELETE NO ACTION ON UPDATE NO ACTION)
what's the best solution here to delete from both table?
Change this constraint to use ON DELETE CASCADE -- which means that if a row is deleted, then any "child" rows will be automatically deleted as well.
Of course take good care of using CASCADE -- only use it when necessary. If you're overzealous with it, and accidentally do a well-placed DELETE, it might end up deleting half of your database. :)
See documentation on foreign key constraints.
I think I see what you're trying to do
If you can't change the table structure, then you could use 2 statements, the first with a sub-select
delete from B where bid IN (select bid from A where name like '%xxxx%');
delete from A where name like '%xxxx%';