问题描述
我想向mysql表中添加新列,但是如果该列已存在,我想忽略该列的添加
i want to add a new column to a mysql table, but i want to ignore the adding of column, if the column already exists
我当前正在使用
ALTER IGNORE TABLE `db`.`tablename` ADD COLUMN `column_name` text NULL;
但这会引发错误:"ERROR 1060 (42S21): Duplicate column name 'column_name'"
即使我使用的是IGNORE,也无法正常工作
even though i am using the IGNORE, this is not working
我希望它能使用普通的SQL语句而不是存储过程来工作
i want this to work using the normal SQL statement, instead of a stored procedure
推荐答案
根据文档:
也就是说,它用于不同的目的,而不是所有的错误.您想要的是类似ALTER TABLE ADD IF NOT EXISTS
的东西,并且该语法不存在.
That is, it is used for a different purpose, not all errors. What you want is something like ALTER TABLE ADD IF NOT EXISTS
, and that syntax doesn't exist.
在存储过程中,可以使用if
语句查看该列是否已经存在(使用INFORMATION_SCHEMA.COLUMNS
).
In a stored procedure, you can use an if
statement to see if the column already exists (using INFORMATION_SCHEMA.COLUMNS
).
此处是显示相同问题的SQL提琴.
Here is a SQL Fiddle that shows the same problem.
这篇关于使用SQL语句更改忽略表添加列(如果不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!