我想向 mysql 表中添加一个新列,但如果该列已经存在,我想忽略该列的添加
我正在使用
ALTER IGNORE TABLE `db`.`tablename` ADD COLUMN `column_name` text NULL;
但这会引发错误:"ERROR 1060 (42S21): Duplicate column name 'column_name'"
即使我使用了 IGNORE,它也不起作用
我希望它使用普通的 SQL 语句而不是存储过程来工作
最佳答案
根据documentation :
IGNORE is a MySQL extension to standard SQL. 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. If IGNORE is not specified, the copy is aborted and rolled back if duplicate-key errors occur. If IGNORE is specified, only one row is used of rows with duplicates on a unique key. The other conflicting rows are deleted. Incorrect values are truncated to the closest matching acceptable value.
也就是用途不同,不全是错误。您想要的是类似 ALTER TABLE ADD IF NOT EXISTS,并且该语法不存在。
在存储过程中,您可以使用 if 语句查看该列是否已存在(使用 INFORMATION_SCHEMA.COLUMNS)。
Here是显示相同问题的 SQL Fiddle。
关于mysql - Alter ignore table add column if not exists 使用 SQL 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22172221/