MySQL DROP all tables, ignoring foreign keys

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

    Building on the answer by @Dion Truter and @Wade Williams, the following shell script will drop all tables, after first showing what it is about to run, and giving you a chance to abort using Ctrl-C.

    #!/bin/bash
    
    DB_HOST=xxx
    DB_USERNAME=xxx
    DB_PASSWORD=xxx
    DB_NAME=xxx
    
    CMD="mysql -sN -h ${DB_HOST} -u ${DB_USERNAME} -p${DB_PASSWORD} ${DB_NAME}"
    
    # Generate the drop statements
    TMPFILE=/tmp/drop-${RANDOM}.sql
    echo 'SET FOREIGN_KEY_CHECKS = 0;' > ${TMPFILE}
    ${CMD} $@ >> ${TMPFILE} << ENDD
        SELECT concat('DROP TABLE IF EXISTS \`', table_name, '\`;')
        FROM information_schema.tables
        WHERE table_schema = '${DB_NAME}';
    ENDD
    echo 'SET FOREIGN_KEY_CHECKS = 1;' >> ${TMPFILE}
    
    # Warn what we are about to do
    echo
    cat ${TMPFILE}
    echo
    echo "Press ENTER to proceed (or Ctrl-C to abort)."
    read
    
    # Run the SQL
    echo "Dropping tables..."
    ${CMD} $@ < ${TMPFILE}
    echo "Exit status is ${?}."
    rm ${TMPFILE}
    

提交回复
热议问题