Removing rows from multiple tables as a single query
I am running the following removal instructions that I want to know if it is possible to combine them at all:
DELETE from schools where visibility like 'revoked'
DELETE FROM bookmark_schools
WHERE school_id NOT IN (SELECT s.id FROM school s)
DELETE FROM school_addresses
WHERE school_id NOT IN (SELECT s.id FROM school s)
DELETE FROM school_highlights
WHERE school_id NOT IN (SELECT s.id FROM school s)
DELETE FROM school_images
WHERE school_id NOT IN (SELECT s.id FROM school s)
...
And so on, I have 15 requests like this. Can you run them together instead of running them separately?
source to share
You can combine these into a single statement as others have pointed out, but note that this will still be a single threaded operation.
If your goal is to improve performance / parallelize this operation, you can write a script that creates 15 different client threads to run statements at the same time.
source to share
You can join the request as below:
DELETE FROM bookmark_schools
FROM bookmark_schools CROSS JOIN
school_addresses CROSS JOIN
school_highlights CROSS JOIN
school_images CROSS JOIN
schools CROSS JOIN
school
WHERE (NOT (bookmark_schools.school_id IN
(SELECT id
FROM school AS s))) AND (NOT (school_addresses.school_id IN
(SELECT id
FROM school AS s))) AND (NOT (school_highlights.school_id IN
(SELECT id
FROM school AS s))) AND (NOT (school_images.school_id IN
(SELECT id
FROM school AS s))) AND (schools.visibility LIKE N'revoked')
source to share
You can achieve what you want, but with some conditions given below -
step1: table engine must be innodb as it doesn't work in myisam.
Step2: Making foreign key references means that all child tables like bookmark_schools, school_Addresses, etc. have a reference to the master tables with the delete cascade enabled.
Step 3. Now you just need to delete rows from the main table, i.e. schools, and the foreign key check will be removed from all child tables.
Further you can use here .
source to share