简体   繁体   中英

Drop Mysql table column with Foreign key constraint

How to drop column with all related foreign key and other constraint in mysql?

Use SET FOREIGN_KEY_CHECKS = 0; and then alter the table that contains the constraint definition. After you're done, turn FOREIGN_KEY_CHECKS back to 1.

AFAIK on MySQL you have to manually delete the constraints before dropping the column.

The ON DELETE CASCADE clause would affect the table only if you created the constraint with that clause and it is only needed to delete the foreign rows connected with that table with that constraint.

if you're using java:

public void deleteColumn(Connection connection, String tableName, String columnName) throws SQLException {
    // Drop all constraints that contain the specified column
    {
        final ResultSet resultSet = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY).executeQuery("select CONSTRAINT_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_SCHEMA = SCHEMA() and TABLE_NAME = '" + tableName + "' and COLUMN_NAME = '" + columnName + "'");
        while (resultSet.next()) {
            final String constraintName = resultSet.getString("CONSTRAINT_NAME");
            connection.createStatement().executeUpdate("ALTER TABLE `" + tableName + "` DROP FOREIGN KEY`" + constraintName + "`"); // Drop the foreign key constraint          
        }
        resultSet.close();
    }

    // Drop all indexes that contain the specified column:
    {
        final ResultSet resultSet = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY).executeQuery("SHOW INDEX FROM `" + tableName + "` where column_name = '" + columnName+ "'");
        while (resultSet.next()) {
            final String keyName = resultSet.getString("Key_name");
            connection.createStatement().executeUpdate("ALTER TABLE `" + tableName + "` DROP INDEX `" + keyName + "`"); // Drop the index               
        }
        resultSet.close();
    }

    // Drop the column:
    connection.createStatement().executeUpdate("ALTER TABLE `" + tableName + "` DROP COLUMN `" + columnName + "`"); // Drop the column
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM