How to alter a MySQL table's foreign key using the command line

前端 未结 4 2130
一整个雨季
一整个雨季 2021-02-13 19:49

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

4条回答
  •  天命终不由人
    2021-02-13 20:19

    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 ...
    

提交回复
热议问题