MySql - Delete all with foreign keys
You want to delete a record in a MySql database but it has foreign keys and gives you the error code 1217
Generate all the applicable delete statements with the following query.
Example
I would like to delete the last record from the TheTable
Statement SELECT Id From TheTable Order by Id DESC LIMIT 1
Turns into the following
WITH
p as (SELECT Id from TheTable order by id desc LIMIT 1)
SELECT CONCAT('DELETE FROM ', TABLE_NAME, ' WHERE ', COLUMN_NAME, ' = ', p.Id, ';') as Stmt
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
JOIN p
WHERE
REFERENCED_TABLE_SCHEMA = 'TheDatabase' AND
REFERENCED_TABLE_NAME = 'TheTable';
I use the Common Table Expression of the WITH
to pull in the single record Id on the root table TheTable
and then fill in the Id
for each of the foreign key tables to produce the following
DELETE FROM TheTableLock WHERE TheTableId = 123;
DELETE FROM TheTableBlackout WHERE TheTableId = 123;
DELETE FROM TheTableListing WHERE TheTableId = 123;
DELETE FROM TheTableListingNearbyPlace WHERE TheTableId = 123;
DELETE FROM TheTableApplicability WHERE TheTableId = 123;
DELETE FROM TheTableShare WHERE TheTableId = 123;
DELETE FROM TheTableStatement WHERE TheTableId = 123;
DELETE FROM TheTableListingBath WHERE TheTableId = 123;
DELETE FROM TheTableDescription WHERE TheTableId = 123;
And then add DELETE FROM TheTable WHERE Id = 123;
to the end and wrap it in a transaction as well if you want for something like, I would run all statements until the ROLLBACK
, verify and then either perform the rollback or commit at that point.
START TRANSACTION;
DELETE FROM TheTableLock WHERE TheTableId = 123;
DELETE FROM TheTableBlackout WHERE TheTableId = 123;
DELETE FROM TheTableListing WHERE TheTableId = 123;
DELETE FROM TheTableListingNearbyPlace WHERE TheTableId = 123;
DELETE FROM TheTableApplicability WHERE TheTableId = 123;
DELETE FROM TheTableShare WHERE TheTableId = 123;
DELETE FROM TheTableStatement WHERE TheTableId = 123;
DELETE FROM TheTableListingBath WHERE TheTableId = 123;
DELETE FROM TheTableDescription WHERE TheTableId = 123;
DELETE FROM TheTable WHERE Id = 123;
-- ROLLBACK;
COMMIT;