MySQL DROP all tables, ignoring foreign keys

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

提交回复
热议问题