N
N
Never Ever2020-01-17 11:18:14
MySQL
Never Ever, 2020-01-17 11:18:14

How to delete data from multiple tables in one query?

I have several hundred tables and I need to remove certain data from them. Tables are named table_1,table_2,table_3 and so on.
Here I find the necessary tables and the query itself what to delete.

SELECT table_name
       FROM INFORMATION_SCHEMA.TABLES
       WHERE table_name LIKE '%table_%'

DELETE
FROM `table_xx`
WHERE `id` = 0

How to combine all this now and make a request like this (it does not work)
DELETE
FROM (SELECT table_name
       FROM INFORMATION_SCHEMA.TABLES
       WHERE table_name LIKE '%table_%')
WHERE id = 0

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Never Ever, 2020-01-17
@Target1

SET @del := (SELECT CONCAT('DELETE FROM ', GROUP_CONCAT(TABLE_NAME SEPARATOR ' WHERE id=0; DELETE FROM ') , ';' )
  AS statement FROM information_schema.TABLES WHERE TABLE_NAME LIKE '%table_%' );
PREPARE stmt FROM @del;
EXECUTE stmt;

R
Roman, 2020-01-17
@Terran37

Perhaps the "Execute Immediate" option will suit you. Read about him.
I'll take a closer look tonight and leave you a comment.

O
Oleg, 2020-01-17
@402d

Triggers have long been invented for this task.
https://dev.mysql.com/doc/refman/8.0/en/trigger-sy...
You need before delete

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question