MySQL DROP all tables, ignoring foreign keys

前端 未结 24 2790
醉梦人生
醉梦人生 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 03:48

    From this answer,

    execute:

      use `dbName`; --your db name here
      SET FOREIGN_KEY_CHECKS = 0; 
      SET @tables = NULL;
      SET GROUP_CONCAT_MAX_LEN=32768;
    
      SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables
      FROM   information_schema.tables 
      WHERE  table_schema = (SELECT DATABASE());
      SELECT IFNULL(@tables, '') INTO @tables;
    
      SET        @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);
      PREPARE    stmt FROM @tables;
      EXECUTE    stmt;
      DEALLOCATE PREPARE stmt;
      SET        FOREIGN_KEY_CHECKS = 1;
    

    This drops tables from the database currently in use. You can set current database using use.


    Or otherwise, Dion's accepted answer is simpler, except you need to execute it twice, first to get the query, and second to execute the query. I provided some silly back-ticks to escape special characters in db and table names.

      SELECT CONCAT('DROP TABLE IF EXISTS `', table_schema, '`.`', table_name, '`;')
      FROM   information_schema.tables
      WHERE  table_schema = 'dbName'; --your db name here
    

提交回复
热议问题