开发者

MySQL ADD IGNORE COLUMN not functioning properly?

I am trying to use the following code to add a column to a table.

ALTER IGNORE TABLE `EWRcarta_history`
    ADD `history_ip` int(10) unsigned NOT NULL DEFAULT '0'

I am using IGNORE because for various reasons that I don't feel like getting into, this code may be called several times. I want to add the column, but ignore the error in case the column already exists. Instead of silently failing and moving on, 开发者_StackOverflowI get the following error:

#1060 - Duplicate column name 'history_ip'

Is there anything I can do to make this work?


I ended up using a function to handle this:

 public static function addColumnIfNotExist($db, $table, $field, $attr)
 {
  if ($db->fetchRow('SHOW columns FROM `'.$table.'` WHERE Field = ?', $field))
  {
   return false;
  }

  return $db->query("ALTER TABLE `".$table."` ADD `".$field."` ".$attr);
 }

and then of course I use the function as follows:

self::addColumnIfNotExist($db, "table", "column", "attributes");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜