SQL: deleting tables with prefix

后端 未结 10 1391
后悔当初
后悔当初 2020-11-30 17:27

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

Note: need to execute it in phpMyAdmin

相关标签:
10条回答
  • 2020-11-30 17:59

    I just wanted to post the exact SQL I used - it's something of a mixture of the top 3 answers:

    SET GROUP_CONCAT_MAX_LEN=10000;
    
    SET @del = (
        SELECT      CONCAT('DROP TABLE ', GROUP_CONCAT(TABLE_NAME), ';')
        FROM        information_schema.TABLES
    
        WHERE       TABLE_SCHEMA = 'database_name'
        AND         TABLE_NAME LIKE 'prefix_%'
    );
    
    PREPARE stmt FROM @del;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    0 讨论(0)
  • 2020-11-30 18:00

    Some of the earlier answers were very good. I have pulled together their ideas with some notions from other answers on the web.

    I needed to delete all tables starting with 'temp_' After a few iterations I came up with this block of code:

    -- Set up variable to delete ALL tables starting with 'temp_'
    SET GROUP_CONCAT_MAX_LEN=10000;
    SET @tbls = (SELECT GROUP_CONCAT(TABLE_NAME)
                   FROM information_schema.TABLES
                  WHERE TABLE_SCHEMA = 'my_database'
                    AND TABLE_NAME LIKE 'temp_%');
    SET @delStmt = CONCAT('DROP TABLE ',  @tbls);
    -- SELECT @delStmt;
    PREPARE stmt FROM @delStmt;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    

    I hope this is useful to other MySQL/PHP programmers.

    0 讨论(0)
  • 2020-11-30 18:01
    SELECT CONCAT("DROP TABLE ", table_name, ";") 
    FROM information_schema.tables
    WHERE table_schema = "DATABASE_NAME" 
    AND table_name LIKE "PREFIX_TABLE_NAME%";
    
    0 讨论(0)
  • 2020-11-30 18:04

    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_%';
    
    0 讨论(0)
提交回复
热议问题