Mysql: Programmatically remove all foreign keys

2019-05-22 19:56发布

问题:

I'm working with a bit of a dodgey database at the moment, there are foreign keys defined in all the wrong places all over the place, I'd like to remove them all and then start from scratch. I don't wish to remove the column, just the foreign key relationships.

How can I remove all foreign keys from an entire database? (Or table by table).

Thanks.

Edit: Forgot to say, I have PHPMyAdmin available to use.

回答1:

Here's a PHP script to loop through the information_schema.key_column_usage table and drop each foreign key:

<?php
$DBNAME = 'dbname';
mysql_connect('localhost', 'username', 'password');

mysql_select_db($DBNAME);
$result = mysql_query("SELECT DISTINCT table_name, constraint_name"
  . " FROM information_schema.key_column_usage"
  . " WHERE constraint_schema = '$DBNAME'"
  . " AND referenced_table_name IS NOT NULL");
while($row = mysql_fetch_assoc($result)) {
  mysql_query("ALTER TABLE `$row[table_name]`"
    . " DROP FOREIGN KEY `$row[constraint_name]`")
    or die(mysql_error());
}
mysql_free_result($result);
mysql_close();
?>


回答2:

I would use a tool to access MySQL Metadata programatically. JDBC, ODBC, MySQL's native API or ADO.NET. From the Metadata extract all existing foreign keys. Loop through all of them and execute:

alter table INSERT_TABLE_NAME_HERE drop constraint INSERT_CONSTRAINT_NAME_HERE;


回答3:

I answered another similar question (Is it possible to drop all foreign key constraints on a table at once in mySQL 5?), but thought it might be worthwhile to include the answer here.

This solution is purely in mysql by creating a procedure to loop through the table constraints and drop them one at a time.

DROP PROCEDURE IF EXISTS dropForeignKeysFromTable;

delimiter ///
create procedure dropForeignKeysFromTable(IN param_table_schema varchar(255), IN param_table_name varchar(255))
begin
    declare done int default FALSE;
    declare dropCommand varchar(255);
    declare dropCur cursor for 
        select concat('alter table ',table_schema,'.',table_name,' DROP FOREIGN KEY ',constraint_name, ';') 
        from information_schema.table_constraints
        where constraint_type='FOREIGN KEY' 
            and table_name = param_table_name
            and table_schema = param_table_schema;

    declare continue handler for not found set done = true;

    open dropCur;

    read_loop: loop
        fetch dropCur into dropCommand;
        if done then
            leave read_loop;
        end if;

        set @sdropCommand = dropCommand;

        prepare dropClientUpdateKeyStmt from @sdropCommand;

        execute dropClientUpdateKeyStmt;

        deallocate prepare dropClientUpdateKeyStmt;
    end loop;

    close dropCur;
end///

delimiter ;

To use the procedure on one of your tables just use the following, replacing table_schema and table_name with your values:

call dropForeignKeysFromTable('table_schema', 'table_name');