title: Mysql deadlock explanation
body: <p>I need some help solving a deadlock situation I am facing.</p>
  
  <p>The below is a test script I have that simulates the issue I am having
  I have a tags table which, per request, might insert/update a lot of entries, all in one transaction.</p>
  
  <p>I know that the deadlock happens because a lot of threads lock the same entries and I would like some feedback as to how I can avoid them</p>
  
  <p>I am running ab -n 100 -c 5 <a href="http://localhost/script.php" rel="nofollow">http://localhost/script.php</a></p>
  
  <p>This the table</p>
  
  <pre><code>CREATE TABLE `tags` 
  (
    `id` INT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(40) COLLATE utf8_unicode_ci DEFAULT NULL,
    `weight` INT(8) DEFAULT NULL,
    `type` ENUM('1','2','3') COLLATE utf8_unicode_ci DEFAULT NULL,
    `modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY  (`id`),
    UNIQUE KEY `tag_name` (`name`)
  ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
  
  &lt;?php
  function go() {
  
      $db = DB::getInstance();
      $db-&gt;start_transaction();
      $tgs = array('electricity', 'emergency', 'trees', 'New Jersey', 'Canada funnelled');
      foreach($tgs as $tg) {
          $arr_tags = array(
              'name' =&gt; $tg,
              'weight' =&gt; '0',
              'type' =&gt; TagTable::PRIMARY
          );
          $tag_instance = new Tag($arr_tags);
          $tag_instance-&gt;save(true);
          // the save method executes a query like the below
          // INSERT INTO tags (weight, type, modified, id, name) VALUES(0, "1", NULL, NULL, "$tag") ON DUPLICATE KEY UPDATE weight = weight+1;
  
      }
      $db-&gt;commit();
  }
  go();
  ?&gt;
  </code></pre>