Using ALTER to drop a column if it exists in MySQL(使用 ALTER 删除 MySQL 中存在的列)
问题描述
如果该列存在,如何使用 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.
这篇关于使用 ALTER 删除 MySQL 中存在的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 ALTER 删除 MySQL 中存在的列


- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01