How to alter a MySQL table's foreign key using

2020-06-11 15:55发布

How to alter an existing table in MySQL, setting foreign key to another table, using the command line?

4条回答
你好瞎i
2楼-- · 2020-06-11 16:31

I was able to achieve the same thing by :

ALTER TABLE the_table_name 
    ADD CONSTRAINT the_name_of_column_you_want_to_use_as_foreign_key 
       REFERENCES other_table_primary_id (Column_name )
查看更多
祖国的老花朵
3楼-- · 2020-06-11 16:37

You have to drop existing foreign key and create another one. For example like this:

ALTER TABLE my_table DROP FOREIGN KEY my_key;
ALTER TABLE my_table ADD CONSTRAINT my_key FOREIGN KEY ('some_id') 
REFERENCES some_new_table ('some_other_id') ON UPDATE CASCADE ON DELETE CASCADE;
查看更多
混吃等死
4楼-- · 2020-06-11 16:37

Execute help alter table at mysql command prompt and the output is very much self explanatory.
Look for add constraint with foreign key clause and apply it on your table.

mysql> help alter table
Name: 'ALTER TABLE'
Description:
Syntax:
ALTER [IGNORE] TABLE tbl_name
    alter_specification [, alter_specification] ...

alter_specification:
    ADD [COLUMN] column_definition [FIRST | AFTER col_name ]
  | ADD [COLUMN] (column_definition,...)
  | ADD {INDEX|KEY} [index_name] [index_type] (index_col_name,...)
  | ADD [CONSTRAINT [symbol]]
        PRIMARY KEY [index_type] (index_col_name,...)
  | ADD [CONSTRAINT [symbol]]
        UNIQUE [INDEX|KEY] [index_name] [index_type] (index_col_name,...)
  | ADD [FULLTEXT|SPATIAL] [INDEX|KEY] [index_name] (index_col_name,...)
  | ADD [CONSTRAINT [symbol]]
        FOREIGN KEY [index_name] (index_col_name,...)
        [reference_definition]
  | ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT}
  | CHANGE [COLUMN] old_col_name column_definition
        [FIRST|AFTER col_name]
  | MODIFY [COLUMN] column_definition [FIRST | AFTER col_name]
  | DROP [COLUMN] col_name
  | DROP PRIMARY KEY
  | DROP {INDEX|KEY} index_name
  | DROP FOREIGN KEY fk_symbol
  | DISABLE KEYS
  | ENABLE KEYS
  | RENAME [TO] new_tbl_name
  | ORDER BY col_name
  | CONVERT TO CHARACTER SET charset_name [COLLATE collation_name]
  | [DEFAULT] CHARACTER SET charset_name [COLLATE collation_name]
  | DISCARD TABLESPACE
  | IMPORT TABLESPACE
  | table_option ...
查看更多
聊天终结者
5楼-- · 2020-06-11 16:41

If you have multiple foreign keys chained together and you get an error that ends with errorno 15x it most likely means that there are other tables that are dependent on the foreign key that you're trying to drop.

To drop the foreign key when you get that error, you will need to do SET FOREIGN_KEY_CHECKS = 0; and then you must first drop the foreign keys on the tables that don't have any other tables dependent on them. You can then successfully drop the foreign keys on the next table up in the chain and so on.

When you're done, make sure you run SET FOREIGN_KEY_CHECKS = 1; again.

查看更多
登录 后发表回答