MySQL Multi-Delete. Is it possible to multi-delete referenced rows? - mysql

If I have a parent table and a child table, is it possible to multi-delete the rows in them without having a "ON DELETE CASCADE" constraint?
In this example:
create table a(id int primary key);
create table b(id int primary key, a_id int,
constraint fkb foreign key (a_id) references a(id));
Is it not possible to do something like this in order to delete rows in tables a and b? :-(
delete a, b
from b
inner join a on a.id = b.a_id
where a.id = ?;
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails
(`erasmusu6`.`b`, CONSTRAINT `fkb` FOREIGN KEY (`a_id`) REFERENCES `a` (`id`))
I would like to multidelete rows but not to set a "ON DELETE CASCADE" constraint. Also I need to filter the DELETE command with a WHERE clause. Is this possible or should I have to make as many DELETEs as tables in the multidelete?

I solve the problem with optimizer hints, by specifying the exact join order in the DELETE command:
delete a, b
from b
STRAIGHT_JOIN a on a.id = b.a_id
where a.id = ?;
MySQL will DELETE b rows first thanks to the optimizer hint STRAIGHT_JOIN.

This is the note from mysql documentation page (http://dev.mysql.com/doc/refman/5.0/en/delete.html):
"If you use a multiple-table DELETE statement involving InnoDB tables for which there are foreign key constraints, the MySQL optimizer might process tables in an order that differs from that of their parent/child relationship. In this case, the statement fails and rolls back. Instead, you should delete from a single table and rely on the ON DELETE capabilities that InnoDB provides to cause the other tables to be modified accordingly."
So, this implies that you are forced not to use multi delete option!
Hope that helps..

Related

MySQL delete with inner join but foreign key constraint fails

I have a MySQL database. I would like to delete all matches where places.match_no > 26 and matches.chart_id = 106.
DELETE matches
FROM kk_matches AS matches
INNER JOIN places ON places.id = matches.place_id
AND places.match_no > 26
WHERE matches.chart_id = 106
This will cause an error:
#1451 - Cannot delete or update a parent row: a foreign key constraint fails...
What to do?
What to do?
Delete the child table dependent row first and then go for deleting parent table row. What you should have actually done is defining CASCADE option while defining your FOREIGN KEY saying ON DELETE CASCADE.
Another option is to have a BEFORE DELETE trigger and in there do DELETE the child table rows
There is another table in your database which has a foreign key to the kk_matches table. Before you can delete a record in the kk_matches table, you need to delete any records in other tables that point to that record in kk_matches. Otherise you would be "orphaning" those other records.
Foreign Keys exist as a means of avoiding these sort of operations that will cause your data to become irrelevant.
You can't delete a row that has a field referenced by a foreign key constraint. You must delete the referencing row first, then delete the row you want (or drop the constraint, if it wasn't intended).
Check this tutorial for more info:
https://www.w3schools.com/sql/sql_foreignkey.asp

SQL: Cannot delete or update parent row: a foreign key constraint fails

Whenever I try to delete a survey from table "survey" like this:
DELETE FROM surveys WHERE survey_id = 77
It prompts me an error stated below:
#1451 - Cannot delete or update a parent row: a foreign key constraint fails ('user_surveys_archive', CONSTRAINT
'user_surveys_archive_ibfk_6' FOREIGN KEY ('user_access_level_id')
REFERENCES 'user_surveys' ('user_access_level_id') ON DELETE NO ACTION
)
First thing: I do not have any such table with this name "user_surveys_archive_ibfk_6"
2nd thing: There is no record of this survey in other tables.
Any idea on how can I delete this record of fix this issue?
Edit
This is the line I found when I export the table Constraints for table surveys
ALTER TABLE `surveys`
ADD CONSTRAINT `surveys_ibfk_1` FOREIGN KEY (`survey_type_id`) REFERENCES `survey_types` (`survey_type_id`) ON DELETE CASCADE ON UPDATE NO ACTION;`
You will need to first remove or update some rows in table user_surveys_archive.
Those rows are related to rows in the user_surveys table.
Likely, there's a foreign key constraint defined on table user_surveys that references rows in surveys you are attempting to delete.
(You'd need to check the foreign key definition, quickest way to get that is a
SHOW CREATE TABLE user_surveys
And look for REFERENCES surveys. (Likely, its a column named survey_id, but we're just guessing without looking at the definitions of the foreign key constraints.)
To find the rows in user_surveys_archive that are preventing the DELETE from happening...
SELECT a.*
FROM user_surveys_archvive a
JOIN user_surveys u
ON u.user_access_level_id = a.user_access_level_id
JOIN surveys s
ON s.survey_id = u.survey_id -- change this to whatever the FK is
WHERE s.survey_id = 77
It's likely that the foreign key constraint from user_surveys to surveys is defined with ON DELETE CASCADE. The attempt to delete rows from surveys identifies rows in user_surveys that should automatically be removed.
The attempt to automatically remove the rows from user_surveys is what's violating the foreign key constraint defined in user_surveys_archive. And that foreign key is not defined with ON DELETE CASCADE.
(The other possibility is that there's a trigger defined that's doing some DML operations, but that would be odd.)
Once you identify the rows, you need to decide what changes to make to allow you to remove rows from surveys.
You can either DELETE the rows, or UPDATE them.
To delete the rows from user_surveys_archive, modify the query above and replace SELECT with DELETE. If the user_access_level_id column in user_surveys_archive allows for NULL values, you can do an update.
Replace SELECT a.* FROM with UPDATE, and add SET a.user_access_level_id = NULL on a line above the WHERE clause...
UPDATE user_surveys_archvive a
JOIN user_surveys u
ON u.user_access_level_id = a.user_access_level_id
JOIN surveys s
ON s.survey_id = u.survey_id -- change this to whatever the FK is
SET a.user_access_level_id = NULL
WHERE s.survey_id = 77
(It seems strange to me that name of the foreign key column is user_access_level_id. But its just a column name, it could be named anything... seems odd to me because of the conventions and patterns that we follow in naming foreign key columns.)
You should allow the foreign key to be NULL and then choose ON DELETE SET NULL.
Personally I would recommend using both "ON UPDATE CASCADE" as well as "ON DELETE SET NULL" to avoid unnecessary complications, however your setup may dictate a different approach.
Hope this helps.
The survey_id of 77 must be referenced in a table possibly named user_surveys_archive. The error is saying the name of the foreign key restraint which is the user_surveys_archive_ibfk_6. If you need to delete survey_id = 77 you will have to delete any child records or other records that reference it as a foreign key.
Edit After posting my answer I saw the comments above. atif the foreign key in the user_surveys_archive table may be named differently but still equal the value of 77 that you are trying to delete, and/or be referencing the survey_id. If that is not the case then there are some other problems within the database. You could try and look at the code for the FK to see how it was made and what fields it is referencing, or run a query to see if there are any records in the user_surveys_archive where the user_access_level_id is = 77.
Edit 2 spencer7593's answer lays out how to run some of the queries mentioned in my answer.

Implement Foreign Key in mysql table

Im trying to restore some old database tables, that when i build them i did not user foreign keys. I have the field that corresponds to the Foreign Key, but i've not set it up in the relations table to which table it connected.
Right know i have a problem because if i try to add that relation, it cannot, because there are some rows deleted in the other table.
Is there any mysql command for checking this type NULL relations for me to delete the rows that i dont need.. and in the end.. add the relation.
TableA
id,
name
TableB
id,
tableA_id,
points
I've deleted some TableA rows.. now i cannot had that relation.
Any mysql command to help, or need to check manually?
Thanks
Assuming that you have PRIMARY KEY constraint at least on TableA.id you can try
-- Delete all orphaned records from TableB
DELETE b
FROM tableb b LEFT JOIN tablea a
ON b.a_id = a.id
WHERE a.id IS NULL;
-- Create a FK constraint
ALTER TABLE TableB
ADD CONSTRAINT fk_a_id FOREIGN KEY (a_id) REFERENCES tablea(id);
Here is SQLFiddle demo

MySQL InnoDB - create CASCADE foreign key constraint when data already exists that violates it?

I have a database that was originally in MyISAM and so had no foreign key constraints. As a result, there are quite a few orphaned rows where the record the foreign key refers to has since been deleted.
To fix this I decided to convert to InnoDB and add the foreign keys, with CASCADE for both updating and deleting. However, when I try to add the foreign key, I get errors like this (from Navicat 8 console):
1452 - Cannot add or update a child row: a foreign key constraint fails
(`database`.`#sql-1358_38d`, CONSTRAINT `#sql-1358_38d_ibfk_1` FOREIGN KEY
(`manufacturerID`) REFERENCES `manufacturer` (`ID`) ON DE)
I know why it's doing this - because of the orphaned rows. Is there a way though to have the creation of the constrain automatically clear out those rows? It will take ages to go through all of the tables and find orphaned rows.
This is one of the queries I'm running just in case it is suspect:
ALTER TABLE part_number ADD CONSTRAINT
FOREIGN KEY(manufacturerID)
REFERENCES manufacturer(ID)
ON DELETE CASCADE
ON UPDATE CASCADE;
write a query that finds the orphaned rows and then use that to delete. e.g
SELECT part_number.id FROM part_number LEFT JOIN manufacturer ON (manufacturer.ID = part_number.manufacturerID) where manufacturer.ID IS NULL
You need to get rid of all irrelevant records before you can add a constraint.
You can do it two ways.
1 Using not exists()
DELETE FROM part_number
WHERE NOT EXISTS (
select id from manufacturer
where part_number.manufacturerID = manufacturer.ID
)
2. Using a temporary table (a bit ugly, but i'll post it too)
-- create a temporary table
CREATE TEMPORARY TABLE `temp_ids`
(
`id` INTEGER
);
-- store all id's that need to be deleted
INSERT INTO `temp_ids`
SELECT part_number.id FROM part_number LEFT JOIN manufacturer ON (manufacturer.ID = part_number.manufacturerID)
WHERE ISNULL(`manufacturer.ID);
-- delete them
DELETE
FROM part_number
WHERE id IN (
SELECT `id` FROM `temp_ids`
);
-- drop the table
DROP TEMPORARY TABLE `temp_ids`;
See my related question: Handling database integrity
After all "dead" records are deleted, you will be able to add a constraint.
Hope this works for you :)

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%';