Using ALTER to drop a column if it exists in MySQL

后端 未结 8 1898
别跟我提以往
别跟我提以往 2020-11-29 02:57

How can ALTER be used to drop a column in a MySQL table if that column exists?

I know I can use ALTER TABLE my_table DROP COLUMN my_column, but that wi

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 03:50

    Perhaps the simplest way to solve this (that will work) is:

    • CREATE new_table AS SELECT id, col1, col2, ... (only the columns you actually want in the final table) FROM my_table;

    • RENAME my_table TO old_table, new_table TO my_table;

    • DROP old_table;

    Or keep old_table for a rollback if needed.

    This will work but foreign keys will not be moved. You would have to re-add them to my_table later; also foreign keys in other tables that reference my_table will have to be fixed (pointed to the new my_table).

    Good Luck...

提交回复
热议问题