title: MySQL - Cannot add or update a child row: a foreign key constraint fails
body: <p>This seems to be a common error, but for the life of me I can't figure this out.</p>
  
  <p>I have a set of InnoDB user tables in MySQL that are tied together via foreign key; the parent <code>user</code> table, and a set of child tables that store email addresses, actions, etc. These are all tied to the parent <code>user</code> table by a foreign key, <code>uid</code>, with all of the parent and child keys being <code>int(10)</code>.</p>
  
  <p>All of the child tables have a <code>uid</code> value with a foreign key constraint pointing to <code>user.uid</code>, and set to <code>ON DELETE CASCADE</code> and <code>ON UPDATE CASCADE</code>. </p>
  
  <p>When I delete a user from <code>user</code>, all of the child constrained entries are removed. However, when I attempt to update a <code>user.uid</code> value, it results in the following error, rather than cascading the <code>uid</code> change to the child tables:</p>
  
  <pre><code>#1452 - Cannot add or update a child row: a foreign key constraint fails (`accounts`.`user_email`, CONSTRAINT `user_email_ibfk_2` FOREIGN KEY (`uid`) REFERENCES `user` (`uid`) ON DELETE CASCADE ON UPDATE CASCADE)
  </code></pre>
  
  <p>I have a feeling I must be missing something obvious here. Removing the key constraint with <code>user_email</code> and attempting to update the value in <code>user</code> results in the same error but for the next alphabetical <code>user</code> child table, so I don't believe it is a table-specific error.</p>
  
  <p>EDIT:</p>
  
  <p>Adding in the results from <code>SHOW ENGINE INNODB STATUS</code>:</p>
  
  <pre><code>------------------------
  LATEST FOREIGN KEY ERROR
  ------------------------
  121018 22:35:41 Transaction:
  TRANSACTION 0 5564387, ACTIVE 0 sec, process no 1619, OS thread id 2957499248 updating or deleting, thread declared inside InnoDB 499
  mysql tables in use 1, locked 1
  17 lock struct(s), heap size 2496, 9 row lock(s), undo log entries 2
  MySQL thread id 3435659, query id 24068634 localhost root Updating
  UPDATE `accounts`.`user` SET `uid` = '1' WHERE `user`.`uid` = 306
  Foreign key constraint fails for table `accounts`.`user_email`:
  ,
    CONSTRAINT `user_email_ibfk_2` FOREIGN KEY (`uid`) REFERENCES `user` (`uid`) ON DELETE CASCADE ON UPDATE CASCADE
  Trying to add in child table, in index `uid` tuple:
  DATA TUPLE: 2 fields;
  ...
  A bunch of hex code
  
  But in parent table `accounts`.`user`, in index `PRIMARY`,
  the closest match we can find is record:
  ...
  A bunch of hex code
  </code></pre>