SQL: deleting tables with prefix

2019-01-08 04:07发布

How to delete my tables who all have the prefix myprefix_?

Note: need to execute it in phpMyAdmin

10条回答
Luminary・发光体
2楼-- · 2019-01-08 04:42

You cannot do it with just a single MySQL command, however you can use MySQL to construct the statement for you:

In the MySQL shell or through PHPMyAdmin, use the following query

SELECT CONCAT( 'DROP TABLE ', GROUP_CONCAT(table_name) , ';' ) 
    AS statement FROM information_schema.tables 
    WHERE table_name LIKE 'myprefix_%';

This will generate a DROP statement which you can than copy and execute to drop the tables.

EDIT: A disclaimer here - the statement generated above will drop all tables in all databases with that prefix. If you want to limit it to a specific database, modify the query to look like this and replace database_name with your own database_name:

SELECT CONCAT( 'DROP TABLE ', GROUP_CONCAT(table_name) , ';' ) 
    AS statement FROM information_schema.tables 
    WHERE table_schema = 'database_name' AND table_name LIKE 'myprefix_%';
查看更多
▲ chillily
3楼-- · 2019-01-08 04:44

I drop table successfully by edit query to like this

SET GROUP_CONCAT_MAX_LEN=10000;
SET FOREIGN_KEY_CHECKS = 0;
SET @tbls = (SELECT GROUP_CONCAT(CONCAT('`', TABLE_NAME, '`'))
           FROM information_schema.TABLES
          WHERE TABLE_SCHEMA = 'pandora'
            AND TABLE_NAME LIKE 'temp_%');
SET @delStmt = CONCAT('DROP TABLE ',  @tbls);
-- SELECT @delStmt;
PREPARE stmt FROM @delStmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1;
查看更多
不美不萌又怎样
4楼-- · 2019-01-08 04:44

You can do that in one command with MySQL:

drop table myprefix_1, myprefix_2, myprefix_3;

You'll probably have to build the table list dynamically in code though.

An alternative approach would be to use the general purpose routine library for MySQL 5.

查看更多
该账号已被封号
5楼-- · 2019-01-08 04:47

Just another solution using GROUP_CONCAT so it will execute one drop query like
DROP TABLE table1,table2,..

SET @Drop_Stm = CONCAT('DROP TABLE ', (
      SELECT GROUP_CONCAT(TABLE_NAME) AS All_Tables FROM information_schema.tables 
      WHERE TABLE_NAME LIKE 'prefix_%' AND TABLE_SCHEMA = 'database_name'
)); 
PREPARE Stm FROM @Drop_Stm; 
EXECUTE Stm;
DEALLOCATE PREPARE Stm;
查看更多
登录 后发表回答