简体   繁体   English

如果不存在,请使用SQL语句忽略表添加列

[英]Alter ignore table add column if not exists using the SQL statement

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 我想在mysql表中添加一个新列,但是如果列已经存在,我想忽略列的添加

i am currently using 我目前正在使用

ALTER IGNORE TABLE `db`.`tablename` ADD COLUMN `column_name` text NULL;

but this is throwing an error saying : "ERROR 1060 (42S21): Duplicate column name 'column_name'" 但这是一个错误说: "ERROR 1060 (42S21): Duplicate column name 'column_name'"

even though i am using the IGNORE, this is not working 即使我使用的是IGNORE,这也行不通

i want this to work using the normal SQL statement, instead of a stored procedure 我希望这使用普通的SQL语句而不是存储过程

According to the documentation : 根据文件

IGNORE is a MySQL extension to standard SQL. IGNORE是标准SQL的MySQL扩展。 It controls how ALTER TABLE works if there are duplicates on unique keys in the new table or if warnings occur when strict mode is enabled. 如果新表中的唯一键上存在重复项,或者启用了严格模式时出现警告,它将控制ALTER TABLE的工作方式。 If IGNORE is not specified, the copy is aborted and rolled back if duplicate-key errors occur. 如果未指定IGNORE,则复制将中止并在发生重复键错误时回滚。 If IGNORE is specified, only one row is used of rows with duplicates on a unique key. 如果指定了IGNORE,则只对一行使用唯一键上具有重复项的行。 The other conflicting rows are deleted. 其他冲突的行将被删除。 Incorrect values are truncated to the closest matching acceptable value. 不正确的值将截断为最接近的匹配可接受值。

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. 你想要的是ALTER TABLE ADD IF NOT EXISTS ,并且该语法不存在。

In a stored procedure, you can use an if statement to see if the column already exists (using INFORMATION_SCHEMA.COLUMNS ). 在存储过程中,您可以使用if语句来查看列是否已存在(使用INFORMATION_SCHEMA.COLUMNS )。

Here is a SQL Fiddle that shows the same problem. 是一个显示相同问题的SQL小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM