MySQL:以前缀开头的DROP TABLE


8

示例:我有30多个表以前缀“ dp_”开头,约有12个表以“ ex_”开头。

问题:如何在一个查询中删除所有以“ dp_”开头的表?


我更新了答案,无需使用存储过程即可执行表的删除。试试看 !!!
RolandoMySQLDBA 2011年

Answers:


11

这是一个接受数据库和前缀字符串作为参数的存储过程:

DELIMITER $$

DROP PROCEDURE DropTablesWithPrefix $$
CREATE PROCEDURE DropTablesWithPrefix(db VARCHAR(64),prfx VARCHAR(20))
StoredProcedure:BEGIN
    DECLARE ndx,maxidx INT;
    DECLARE giventable,SQLSTMT VARCHAR(500);

    CREATE TABLE TableZapList
    (
        droptablesql VARCHAR(512),
        idx INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    ) ENGINE=MyISAM;

    INSERT INTO TableZapList (droptablesql)
    SELECT CONCAT('DROP TABLE ',table_schema,'.',table_name)
    FROM information_schema.tables
    WHERE table_schema = db AND SUBSTR(table_name,LENGTH(prfx)) = prfx;
    SELECT COUNT(1) INTO maxid FROM TableZapList;

    IF maxid = 0 THEN
        LEAVE StoredProcedure;
    END IF;<BR>

    SET ndx = 0;
    WHILE ndx < maxid DO
        SET ndx = ndx + 1;
        SELECT droptablesql INTO SQLSTMT FROM TableZapList WHERE idx = ndx;
        SET @sql = SQLSTMT;
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END WHILE;<BR>

    SELECT droptablesql FROM TableZapList;
    DROP TABLE TableZapList;
END;

DELIMITER ;

更新2011-07-12 14:55 EDT

我只是想到了一种更清洁,更简单的方法。无需使用存储过程,只需使用GROUP_CONCAT函数将所有表收集到zap。然后组成一个查询:

这是一个查询,以删除当前数据库中所有以wp_pol开头的表:

SELECT CONCAT('DROP TABLE ',GROUP_CONCAT(CONCAT(table_schema,'.',table_name)),';')
FROM information_schema.tables
WHERE table_schema=database()
AND table_name like 'wp_pol%';

接下来要做的是将其结果存储在

SELECT CONCAT('DROP TABLE ',GROUP_CONCAT(CONCAT(table_schema,'.',table_name)),';')
INTO @dropcmd
FROM information_schema.tables
WHERE table_schema=database()
AND table_name like 'wp_pol%';

最后一件事是使用以下三个(3)命令执行动态SQL:

PREPARE s1 FROM @dropcmd;
EXECUTE s1;
DEALLOCATE PREPARE s1;

这是在Windows中使用MySQL 5.5.12的演示,该演示有效:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.5.12 MySQL Community Server (GPL)

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

MySQL (Current test) :: use garbage
Database changed
MySQL (Current garbage) :: show tables;
+------------------------------+
| Tables_in_garbage            |
+------------------------------+
| datas                        |
| rolando                      |
| wp_commentmeta               |
| wp_comments                  |
| wp_contact_form_7            |
| wp_links                     |
| wp_most_read_hits            |
| wp_options                   |
| wp_pollsa                    |
| wp_pollsip                   |
| wp_pollsq                    |
| wp_postmeta                  |
| wp_posts                     |
| wp_posts_idtracker           |
| wp_tantan_wordpress_s3_cache |
| wp_term_relationships        |
| wp_term_taxonomy             |
| wp_terms                     |
| wp_usermeta                  |
| wp_users                     |
| wp_w3tc_cdn_queue            |
+------------------------------+
21 rows in set (0.00 sec)

MySQL (Current garbage) :: SELECT CONCAT('DROP TABLE ',GROUP_CONCAT(CONCAT(table_schema,'.',table_name)),';') INTO @dropcmd FROM information_schema.tables WHERE table_schema=database() AND table_name like 'wp_pol%';
Query OK, 1 row affected (0.00 sec)

MySQL (Current garbage) :: SELECT @dropcmd;
+--------------------------------------------------------------------+
| @dropcmd                                                           |
+--------------------------------------------------------------------+
| DROP TABLE garbage.wp_pollsa,garbage.wp_pollsip,garbage.wp_pollsq; |
+--------------------------------------------------------------------+
1 row in set (0.00 sec)

MySQL (Current garbage) :: PREPARE s1 FROM @dropcmd; EXECUTE s1; DEALLOCATE PREPARE s1;
Query OK, 0 rows affected (0.00 sec)
Statement prepared

Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

MySQL (Current garbage) :: show tables;
+------------------------------+
| Tables_in_garbage            |
+------------------------------+
| datas                        |
| rolando                      |
| wp_commentmeta               |
| wp_comments                  |
| wp_contact_form_7            |
| wp_links                     |
| wp_most_read_hits            |
| wp_options                   |
| wp_postmeta                  |
| wp_posts                     |
| wp_posts_idtracker           |
| wp_tantan_wordpress_s3_cache |
| wp_term_relationships        |
| wp_term_taxonomy             |
| wp_terms                     |
| wp_usermeta                  |
| wp_users                     |
| wp_w3tc_cdn_queue            |
+------------------------------+
18 rows in set (0.00 sec)

MySQL (Current garbage) ::

试试看 !!!


Rolandos脚本可以工作,但是如果您有很多表或表名很长,则可能需要增加参数group_concat_max_len:SET SESSION group_concat_max_len = 1000000;
JohnP

我没有更改group + concat_max_len,而是使用了一个具有限制的子查询,并逐步执行了删除操作
pedromanoel 2013年

中的SUBSTR条件INSERT应为:SUBSTR(table_name, 1, LENGTH(prfx)) = prfx然后运行正常。
劳伦特

8

首先,在Unix提示符下生成一个脚本来执行此操作:

$  echo "select concat('drop table ', table_name, ';') from information_schema.tables where table_name like 'prefix_%';" |mysql --user=root --password=blah --batch >drop.sql

用您自己的前缀替换。该--batch选项抑制MySQL默认情况下的格式化格式,因此您可以生成可运行的SQL脚本。

查看脚本,如果看起来不错,请drop.sqlmysql>提示符下运行。


我已经准备好了一个php helper脚本来做到这一点,但是我想知道是否可以使用单个查询来完成。
poelinca 2011年

1
简单答案:否。复杂答案:是,如果将其包装在存储过程中。因此,您可以在一个命令中执行它,但它与调用脚本相同。
Gaius

4

您应该在系统表中查询那些表名,并构建一个字符串以动态执行它。在SQL Server中,我将执行以下操作:

declare @x varchar(max), @enter char(2);
select @x = '', @enter = char(13)+char(10);

Select @x = @x + 'drop table ' + table_name + ';' + @enter    
from information_schema.tables    
where table_name like '%accounting%'

print @x
execute (@x);

现在,您必须在MySQL中找到相应的系统表。


我非常仔细地阅读了您的答案。这就是我的答案的代名词。尽管在SQL Server方言中,原则上您的答案是第一个正确答案。+1 !!!
RolandoMySQLDBA 2011年

3

要回答您的问题,不。不在MySQL中使用单个命令/查询。您必须链接命令。

但是,如果您想实现自己的目标,这是一种方法:

在bash脚本中,如下所示:

#/bin/bash
TABLES=`mysql -s -e "SELECT CONCAT(TABLE_SCHEMA,'.',TABLE_NAME) AS T FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'dp_%'" -u user -p`

for i in $TABLES; 
do 
 echo "DROP TABLE $i;" >> drops.sql ; 
done

cat drops.sql

然后查看drops.sql文件。如果一切都很好,请进行BACKUP,然后...

mysql -u username -p -v --show-warnings < drops.sql

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.