MySQL bulk drop table where table like?

笑着哭i 提交于 2019-12-17 21:52:31

问题


DROP TABLE (
SELECT table_name
FROM information_schema.`TABLES`
WHERE table_schema = 'myDatabase' AND table_name LIKE BINARY 'del%');

I know this doesn't work! What is the equivalent for something like this in SQL? I can whip out a simple Python script to do this but was just wondering if we can do something with SQL directly. I am using MySQL. Thank you!


回答1:


You can use prepared statements -

SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name,'`') INTO @tables FROM information_schema.tables 
  WHERE table_schema = 'myDatabase' AND table_name LIKE BINARY 'del%';

SET @tables = CONCAT('DROP TABLE ', @tables);
PREPARE stmt1 FROM @tables;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

It will generate and execute a statement like this -

DROP TABLE myDatabase.del1, myDatabase.del2, myDatabase.del3;



回答2:


A minor improvement to @Devart's answer:

SET @tables = NULL;
SELECT GROUP_CONCAT(table_schema, '.`', table_name, '`') INTO @tables FROM
(select * from
 information_schema.tables 
  WHERE table_schema = 'myDatabase' AND table_name LIKE 'del%'
  LIMIT 10) TT;

SET @tables = CONCAT('DROP TABLE ', @tables);
select @tables;
PREPARE stmt1 FROM @tables;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

This script should be executed repeatedly until the console's output is NULL

The changes are:

  1. backtick (`) wrapping the table name (if it contains non standard characters)
  2. added a LIMIT to avoid the truncation issue I commented about
  3. added a "print" (select @tables;) to have some kind of control when to stop executing the script



回答3:


If you just need to quickly drop a bunch of tables (not in pure SQL, so not directly answering this question) a one line shell command can do it:

echo "show tables like 'fsm%'" | mysql | tail +2 | while read t; do echo "drop table \`$t\`;"; done | mysql



回答4:


I found it useful to add an IFNULL to Devart's solutions to avoid generating an error if there are no tables matching the query.

SET @tables = IFNULL(CONCAT('DROP TABLE ', @tables),'SELECT NULL;');



回答5:


You can do this quickly and easily if you have phpMyAdmin available and the requirement is to drop tables with a specific prefix. Go to the database you want, and show the list of all the tables. Since tables are shown in alphabetic order, the tables with the prefix for deletion will all appear together. Go to the first one, and click the tick box on the left hand side. Then scroll down to the last table with the prefix, hold down shift, and click the tick box. That results in all the tables with the prefix being ticked. Go to the bottom of the list, and select the action drop for all selected tables. Go through with the deletion, checking that the SQL generated looks right!



来源:https://stackoverflow.com/questions/11053116/mysql-bulk-drop-table-where-table-like

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!