Search code examples
mysqlsqlmysql-error-1060

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, I get the following error:

#1060 - Duplicate column name 'history_ip'

Is there anything I can do to make this work?


Solution

  • 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");