13

如何使用命令行更改 MySQL 中的现有表,将外键设置为另一个表?

4

4 回答 4

20

您必须删除现有的foreign key并创建另一个。例如像这样:

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;
于 2012-06-17T18:24:31.030 回答
3

help alter table在命令提示符下执行,mysql输出非常不言自明。
查找add constraintwithforeign key子句并将其应用于您的表。

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 ...
于 2012-06-17T18:26:48.123 回答
2

如果您有多个外键链接在一起并且您收到一个以它结尾的错误,errorno 15x这很可能意味着还有其他表依赖于您尝试删除的外键。

要在出现该错误时删除外键,您需要SET FOREIGN_KEY_CHECKS = 0;先删除没有任何其他表依赖于它们的表上的外键。然后,您可以成功地将外键放在链中的下一个表上,依此类推。

完成后,请确保SET FOREIGN_KEY_CHECKS = 1;再次运行。

于 2014-09-03T13:51:21.113 回答
2

我能够通过以下方式实现相同的目标:

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 )
于 2014-08-03T12:40:02.967 回答