<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:ent="http://www.purl.org/NET/ENT/1.0/" version="2.0">
  <channel>
    <title>Curiouser and Curiouser! on sql</title>
    <link>http://matt.blogs.it/</link>
    <description>RSS feed for topic sql</description>
    <copyright>Copyright 2006 Matt Mower. Some rights reserved.</copyright>
    <generator>Squib/0.5.0.382</generator>
    <managingEditor>self@mattmower.com</managingEditor>
    <webMaster>self@mattmower.com</webMaster>
    <language>en-gb</language>
    <item>
      <title>An unexpected piece of joinery</title>
      <link>http://matt.blogs.it/entries/00002453.html</link>
      <pubDate>Thu, 07 Dec 2006 14:56:45 +0000</pubDate>
      <description>&lt;p&gt;Yesterday I found myself wanting to build a tree structure in a relational database and I needed to update the rows of the database with a parent_id column. The values for this column come from the same database table based upon a shared value. After thinking about it for a few minutes I came up with this (Names of tables and columns have been changed to protect the innocent):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;UPDATE things SET parent_id = (SELECT id FROM things WHERE value = x) WHERE value = y
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The nested SELECT was supposed to look up the ID of the parent row so that the UPDATE could assign it to the child row. This seemed to make sense to me but MySQL wasn't having any of it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ERROR 1093 (HY000): You can't specify target table 'things' for update in FROM clause
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This had me scratching my head for some time. I hit the MySQL documentation and, after some browsing, realised that you can do joins in UPDATE queries. I'd never thought of it. The real solution looks something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;UPDATE things t1, things t2 SET t1.parent_id = t2.id WHERE t1.value = x AND t2.value = y
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Quite a neat trick. Of course an hour after I figured this out I decided to completely change my approach to the underlying problem so it was a complete waste of time solving the problem. Oh well!&lt;/p&gt;</description>
      <guid isPermaLink="true">http://matt.blogs.it/entries/00002453.html</guid>
      <ent:cloud ent:href="http://matt.blogs.it/topics/">
      </ent:cloud>
    </item>
  </channel>
</rss>
