Answers:
MySQL ALTER TABLE
没有IF EXISTS
规范。
如果您需要定期执行此操作,则可以使用存储的proc或编程语言来执行以下操作:
伪代码:
使用以下SQL查找列是否存在:
SELECT column_name
FROM INFORMATION_SCHEMA
。COLUMNS
WHERE TABLE_SCHEMA
= [数据库名称] AND TABLE_NAME
= [表名称];
如果上述查询返回结果,则表明该列存在,否则,您可以继续创建该列。
column_name
不存在。我将查询重新表述为:SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='[Schema_name]' AND TABLE_NAME='[Table_name]' and column_name='[Column_name]';
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='[Schema_name]' AND TABLE_NAME='[Table_name]' AND column_name='[Column_name]'
您可以使用已经在另一StackOverFlow帖子中提到的解决方案:(参考:https://stackoverflow.com/a/31989541/)
MySQL-ALTER TABLE添加一列(如果不存在):
SET @dbname = DATABASE();
SET @tablename = "tableName";
SET @columnname = "colName";
SET @preparedStatement = (SELECT IF(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE
(table_name = @tablename)
AND (table_schema = @dbname)
AND (column_name = @columnname)
) > 0,
"SELECT 1",
CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " INT(11);")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
下面为我工作:
SELECT count(*)
INTO @exist
FROM information_schema.columns
WHERE table_schema = 'mydatabase'
and COLUMN_NAME = 'mycolumn'
AND table_name = 'mytable' LIMIT 1;
set @query = IF(@exist <= 0, 'ALTER TABLE mydatabase.`mytable` ADD COLUMN `mycolumn` MEDIUMTEXT NULL',
'select \'Column Exists\' status');
prepare stmt from @query;
EXECUTE stmt;