MySQL DROP all tables, ignoring foreign keys

前端 未结 24 2571
醉梦人生
醉梦人生 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

    This is a pretty old post, but none of the answers here really answered the question in my opinion, so I hope my post will help people!

    I found this solution on another question that works really well for me:

    mysql -Nse 'show tables' DB_NAME | while read table; do mysql -e "SET FOREIGN_KEY_CHECKS=0; truncate table \`$table\`" DB_NAME; done
    

    That will actually empty all your tables in the database DB_NAME, and not only display the TRUNCATE command line.

    Hope this helps!

    0 讨论(0)
  • 2020-12-02 03:49

    If in linux (or any other system that support piping, echo and grep) you can do it with one line:

    echo "SET FOREIGN_KEY_CHECKS = 0;" > temp.txt; \
    mysqldump -u[USER] -p[PASSWORD] --add-drop-table --no-data [DATABASE] | grep ^DROP >> temp.txt; \
    echo "SET FOREIGN_KEY_CHECKS = 1;" >> temp.txt; \
    mysql -u[USER] -p[PASSWORD] [DATABASE] < temp.txt;
    

    I know this is an old question, but I think this method is fast and simple.

    0 讨论(0)
  • 2020-12-02 03:50

    One-step solution without copying returned value from SQL Select query using procedure.

    SET FOREIGN_KEY_CHECKS = 0
    
    SET @TABLES = NULL;
    SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name,'`') INTO @TABLES FROM information_schema.tables 
      WHERE table_schema = 'databaseName';
    
    SET @TABLES = CONCAT('DROP TABLE IF EXISTS ', @TABLES);
    
    PREPARE stmt FROM @TABLES;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    SET FOREIGN_KEY_CHECKS = 1
    
    0 讨论(0)
  • 2020-12-02 03:51

    A one liner to drop all tables from a given database:

    echo "DATABASE_NAME"| xargs -I{} sh -c "mysql -Nse 'show tables' {}| xargs -I[] mysql -e 'SET FOREIGN_KEY_CHECKS=0; drop table []' {}"
    

    Running this will drop all tables from database DATABASE_NAME.

    And a nice thing about this is that the database name is only written explicitly once.

    0 讨论(0)
  • 2020-12-02 03:51

    Drop all the tables from database with a single line from command line:

    mysqldump -u [user_name] -p[password] -h [host_name] --add-drop-table --no-data [database_name] | grep ^DROP | mysql -u [user_name] -p[password] -h [host_name] [database_name]
    

    Where [user_name], [password], [host_name] and [database_name] have to be replaced with a real data (user, password, host name, database name).

    0 讨论(0)
  • 2020-12-02 03:53

    You can do:

    select concat('drop table if exists ', table_name, ' cascade;')
      from information_schema.tables;
    

    Then run the generated queries. They will drop every single table on the current database.

    Here is some help on drop table command.

    0 讨论(0)
提交回复
热议问题