MySQL DROP all tables, ignoring foreign keys

前端 未结 24 2572
醉梦人生
醉梦人生 2020-12-02 03:44

Is there a nice easy way to drop all tables from a MySQL database, ignoring any foreign key constraints that may be in there?

相关标签:
24条回答
  • 2020-12-02 04:03

    Here's a cursor based solution. Kinda lengthy but works as a single SQL batch:

    DROP PROCEDURE IF EXISTS `drop_all_tables`;
    
    DELIMITER $$
    CREATE PROCEDURE `drop_all_tables`()
    BEGIN
        DECLARE _done INT DEFAULT FALSE;
        DECLARE _tableName VARCHAR(255);
        DECLARE _cursor CURSOR FOR
            SELECT table_name 
            FROM information_schema.TABLES
            WHERE table_schema = SCHEMA();
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = TRUE;
    
        OPEN _cursor;
    
        REPEAT FETCH _cursor INTO _tableName;
    
        IF NOT _done THEN
            SET @stmt_sql = CONCAT('DROP TABLE ', _tableName);
            PREPARE stmt1 FROM @stmt_sql;
            EXECUTE stmt1;
            DEALLOCATE PREPARE stmt1;
        END IF;
    
        UNTIL _done END REPEAT;
    
        CLOSE _cursor;
    
    END$$
    
    DELIMITER ;
    
    call drop_all_tables(); 
    
    DROP PROCEDURE IF EXISTS `drop_all_tables`;
    
    0 讨论(0)
  • 2020-12-02 04:03

    In a Linux shell like bash/zsh:

    DATABASE_TO_EMPTY="your_db_name";
    { echo "SET FOREIGN_KEY_CHECKS = 0;" ; \
      mysql "$DATABASE_TO_EMPTY" --skip-column-names -e \
      "SELECT concat('DROP TABLE IF EXISTS ', table_name, ';') \
       FROM information_schema.tables WHERE table_schema = '$DATABASE_TO_EMPTY';";\
      } | mysql "$DATABASE_TO_EMPTY"
    

    This will generate the commands, then immediately pipe them to a 2nd client instance which will delete the tables.

    The clever bit is of course copied from other answers here - I just wanted a copy-and-pasteable one-liner (ish) to actually do the job the OP wanted.

    Note of course you'll have to put your credentials in (twice) in these mysql commands, too, unless you have a very low security setup. (or you could alias your mysql command to include your creds.)

    0 讨论(0)
  • 2020-12-02 04:04

    In php its as easy as:

    $pdo = new PDO('mysql:dbname=YOURDB', 'root', 'root');
    
    $pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
    
    $query = "SELECT concat('DROP TABLE IF EXISTS ', table_name, ';')
              FROM information_schema.tables
              WHERE table_schema = 'YOURDB'";
    
    foreach($pdo->query($query) as $row) {
        $pdo->exec($row[0]);
    }
    
    $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
    

    Just remember to change YOURDB to the name of your database, and obviously the user/pass.

    0 讨论(0)
  • 2020-12-02 04:07
    DB="your database name" \
        && mysql $DB < "SET FOREIGN_KEY_CHECKS=0" \
        && mysqldump --add-drop-table --no-data $DB | grep 'DROP TABLE' | grep -Ev "^$" | mysql $DB \
        && mysql $DB < "SET FOREIGN_KEY_CHECKS=1"
    
    0 讨论(0)
  • 2020-12-02 04:08

    Simple and clear (may be).

    Might not be a fancy solution, but this worked me and saved my day.

    Worked for Server version: 5.6.38 MySQL Community Server (GPL)

    Steps I followed:

     1. generate drop query using concat and group_concat.
     2. use database
     3. disable key constraint check
     4. copy the query generated from step 1
     5. enable key constraint check
     6. run show table
    

    MySQL shell

    mysql> SYSTEM CLEAR;
    mysql> SELECT CONCAT('DROP TABLE IF EXISTS `', GROUP_CONCAT(table_name SEPARATOR '`, `'), '`;') AS dropquery FROM information_schema.tables WHERE table_schema = 'emall_duplicate';
    +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | dropquery                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
    +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`; |
    +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    1 row in set (0.00 sec)
    
    mysql> USE emall_duplicate;
    Database changed
    mysql> SET FOREIGN_KEY_CHECKS = 0;                                                                                                                                                   Query OK, 0 rows affected (0.00 sec)
    
    // copy and paste generated query from step 1
    mysql> DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`;
    Query OK, 0 rows affected (0.18 sec)
    
    mysql> SET FOREIGN_KEY_CHECKS = 1;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> SHOW tables;
    Empty set (0.01 sec)
    
    mysql> 
    

    0 讨论(0)
  • 2020-12-02 04:10

    Here is an automated way to do this via a bash script:

    host=$1
    dbName=$2
    user=$3
    password=$4
    
    if [ -z "$1" ]
    then
        host="localhost"
    fi
    
    # drop all the tables in the database
    for i in `mysql -h$host -u$user -p$password $dbName -e "show tables" | grep -v Tables_in` ; do  echo $i && mysql -h$host -u$user -p$password $dbName -e "SET FOREIGN_KEY_CHECKS = 0; drop table $i ; SET FOREIGN_KEY_CHECKS = 1" ; done
    
    0 讨论(0)
提交回复
热议问题