2011-06-06 186 views

回答

2

據我所知在MySQL 你必須刪除列前手動刪除的約束。

只有當您使用該子句創建約束時,ON DELETE CASCADE子句纔會影響該表,並且只需要刪除與該約束關聯的外部行。

4

使用SET FOREIGN_KEY_CHECKS = 0;然後更改包含約束定義的表。大功告成後,關閉FOREIGN_KEY_CHECKS回1

1

,如果你使用的是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 
} 
+0

你救我說!謝謝!這正是我正在尋找的,所以我可以使用ForeignKey刪除一列。 – marcolopes 2017-06-16 20:27:39