Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When you <code>INSERT</code> new records, given that you don't want to do two inserts for some reason, <a href="http://dev.mysql.com/doc/refman/5.0/en/triggers.html" rel="nofollow">using a trigger</a> to insert into the second table will work. For <code>UPDATE</code> and <code>DELETE</code> you might want to look at the <code>CASCADE</code> option with <a href="http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html" rel="nofollow">foreign keys</a>. If all you are doing is keeping the data consistent between tables, that's exactly what cascade is for.</p> <p>When you create table2 you just add a foreign key like this:</p> <pre><code>FOREIGN KEY (id, username) REFERENCES table1(id, username) ON UPDATE CASCADE ON DELETE CASCADE </code></pre> <p>Then whenever you alter table1 the changes will automatically get pushed through to table2. </p> <p><strong>Couple prerequisites for this to work:</strong></p> <ol> <li>You have to use a <a href="http://dev.mysql.com/doc/refman/5.1/en/storage-engines.html" rel="nofollow">storage engine</a> that supports foreign keys, something like <code>InnoDB</code> and not <code>MyISAM</code></li> <li>You need to have an index on <code>(id,username)</code> in table1; the foriegn key needs to match a key in the parent table</li> <li>You should read the doc page for <a href="http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html" rel="nofollow">foreign keys</a>. There are a couple other ways you can tweak them, and you should figure out what works best for your purposes.</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload