使用 ALTER 删除 MySQL 中存在的列

2021-11-20 00:00:00 mysql ddl mysql4

如果该列存在,如何使用 ALTER 删除 MySQL 表中的列?

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

我知道我可以使用 ALTER TABLE my_table DROP COLUMN my_column,但是如果 my_column 不存在,这将引发错误.是否有条件删除列的替代语法?

I know I can use ALTER TABLE my_table DROP COLUMN my_column, but that will throw an error if my_column does not exist. Is there alternative syntax for dropping the column conditionally?

我使用的是 MySQL 4.0.18 版.

I'm using MySQL version 4.0.18.

推荐答案

对于 MySQL,没有: MySQL 功能请求.

无论如何,允许这可以说是一个非常糟糕的主意:IF EXISTS 表明您正在对具有(对您而言)未知结构的数据库运行破坏性操作.在某些情况下,这对于快速而繁琐的本地工作是可以接受的,但是如果您想针对生产数据(在迁移等中)运行这样的语句,那么您就是在玩火.

Allowing this is arguably a really bad idea, anyway: IF EXISTS indicates that you're running destructive operations on a database with (to you) unknown structure. There may be situations where this is acceptable for quick-and-dirty local work, but if you're tempted to run such a statement against production data (in a migration etc.), you're playing with fire.

但是如果您坚持,那么简单地首先在客户端检查是否存在或捕获错误并不困难.

But if you insist, it's not difficult to simply check for existence first in the client, or to catch the error.

MariaDB 从 10.0.2 开始还支持以下内容:

MariaDB also supports the following starting with 10.0.2:

DROP [COLUMN] [IF EXISTS] col_name 

我.e.

ALTER TABLE my_table DROP IF EXISTS my_column;

但是,依赖仅由 MySQL 的几个分支之一支持的非标准功能可以说是一个坏主意.

But it's arguably a bad idea to rely on a non-standard feature supported by only one of several forks of MySQL.

相关文章