title: MySQL many-to-many schema setup
body: <p>I'm setting up a mysql db with posts and tags that looks like this:</p>
  
  <pre><code>posts    
  +-------------+--------------+------+-----+-------------------+----------------+
  | Field       | Type         | Null | Key | Default           | Extra          |
  +-------------+--------------+------+-----+-------------------+----------------+
  | id          | int(11)      | NO   | PRI | NULL              | auto_increment |
  [...]
  
  tags
  +-------+--------------+------+-----+---------+----------------+
  | Field | Type         | Null | Key | Default | Extra          |
  +-------+--------------+------+-----+---------+----------------+
  | id    | int(11)      | NO   | PRI | NULL    | auto_increment |
  | tag   | varchar(255) | NO   | UNI | NULL    |                |
  +-------+--------------+------+-----+---------+----------------+
  
  post_tag_map
  +------------+---------+------+-----+---------+-------+
  | Field      | Type    | Null | Key | Default | Extra |
  +------------+---------+------+-----+---------+-------+
  | post_id    | int(11) | NO   | PRI | NULL    |       |
  | tag_id     | int(11) | NO   | PRI | NULL    |       |
  +------------+---------+------+-----+---------+-------+
  </code></pre>
  
  <p>The tags will be shared between multiple posts; 'red' may be used by post 5 and 10.</p>
  
  <p><strong>My question is:</strong> how do I prevent the deletion of a tag if it is being used by more than one post and delete it if it isn't?</p>
  
  <p><strong>Note:</strong> I am using Foreign Keys which I thought would take care of this issue but it doesn't seem to be working:</p>
  
  <pre><code>CREATE TABLE `post_tag_map` (
    `post_id` int(11) NOT NULL,
    `tag_id` int(11) NOT NULL,
    PRIMARY KEY (`post_id`,`tag_id`),
    FOREIGN KEY (`post_id`) REFERENCES posts(`id`),
    FOREIGN KEY (`tag_id`) REFERENCES tag(`id`)
  )  
  </code></pre>