如果ALTER存在于MySQL中,则使用ALTER删除它 [英] Using ALTER to drop a column if it exists in MySQL

查看:427
本文介绍了如果ALTER存在于MySQL中,则使用ALTER删除它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果该列存在,如何使用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,没有: 无论如何,允许这样做是一个很糟糕的主意: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 

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

这篇关于如果ALTER存在于MySQL中,则使用ALTER删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆