title: Altering MySQL table to add foreign key constraint leads to errors
body: <h1>Question:</h1> 
  
  <p>Why am I getting errors when trying to alter a table with a foreign key constraint?</p>
  
  <h1>Details:</h1>
  
  <p>I have 1 table, <code>HSTORY</code> which I use as a base table for all other specific history tables (ie. <code>USER_HISTORY</code>, <code>BROWSER_HISTORY</code>, <code>PICTURE_HISTORY</code>...).  I have also included the <code>PICTURE</code> and <code>USER</code> tables as they get called as well.</p>
  
  <p><strong>HISTORY table:</strong></p>
  
  <pre><code>CREATE TABLE IF NOT EXISTS HISTORY
  (
     ID        INT NOT NULL AUTO_INCREMENT,
     VIEWERID  INT NOT NULL ,
     VIEWDATE  TIMESTAMP NOT NULL DEFAULT NOW(),
  
     PRIMARY KEY (ID),
     FOREIGN KEY (VIEWERID) REFERENCES USER(ID)
  )
  engine=innodb;
  </code></pre>
  
  <p><strong>USER table:</strong> (in case anyone is curious)</p>
  
  <pre><code>CREATE TABLE IF NOT EXISTS USER
  (
     ID        INT NOT NULL AUTO_INCREMENT,
  
     PRIMARY KEY (ID)
  )
  engine=innodb;
  </code></pre>
  
  <p><strong>PICTURE table:</strong> (in case anyone is curious)</p>
  
  <pre><code>CREATE TABLE IF NOT EXISTS PICTURE
  (
     ID        INT NOT NULL AUTO_INCREMENT,
  
     PRIMARY KEY (ID)
  )
  engine=innodb;
  </code></pre>
  
  <p><strong>PICTURE_HISTORY table:</strong></p>
  
  <pre><code>CREATE TABLE IF NOT EXISTS PICTURE_HISTORY LIKE HISTORY;
  
  ALTER TABLE PICTURE_HISTORY
  ADD FOREIGN KEY (FOREIGNID) REFERENCES PICTURE(ID);
  </code></pre>
  
  <p>However, when I do this, I get:</p>
  
  <pre><code>Key column 'FOREIGNID' doesn't exist in table
  </code></pre>
  
  <p>I take this to mean that I have to first create <code>FOREIGNID</code>, but in many of the examples on SO, the above should work. Anyone know why this is occurring? </p>