<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>my crazy blog &#187; nested sets</title>
	<atom:link href="http://mycrazydream.net/wp/tag/nested-sets/feed/" rel="self" type="application/rss+xml" />
	<link>http://mycrazydream.net/wp</link>
	<description>c o d e  p o e t r y  a n d  h i g h  c r a z i n e s s</description>
	<lastBuildDate>Fri, 20 Jan 2012 07:01:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Nested Sets in a MySQL Database</title>
		<link>http://mycrazydream.net/wp/2009/04/nested-sets-for-category-structure-in-a-mysql-database/</link>
		<comments>http://mycrazydream.net/wp/2009/04/nested-sets-for-category-structure-in-a-mysql-database/#comments</comments>
		<pubDate>Sat, 04 Apr 2009 17:40:15 +0000</pubDate>
		<dc:creator>mcd</dc:creator>
				<category><![CDATA[SQL: Structured Query Language]]></category>
		<category><![CDATA[adjacency model]]></category>
		<category><![CDATA[hierarchical data]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[nested sets]]></category>

		<guid isPermaLink="false">http://mycrazydream.net/?p=69</guid>
		<description><![CDATA[The Adjacency Model vs. Nested Sets Most developers have had to manage hierarchical data at some point, often in the form of categories on a website. The problem is, sql offers no real solution to handling hierarchy&#8230; not without a little creativity that is. The traditional solution is called, in geek vernacular, the adjacency model. [...]]]></description>
			<content:encoded><![CDATA[<h2>The Adjacency Model vs. Nested Sets</h2>
<p>Most developers have had to manage hierarchical data at some point, often in the form of categories on a website. The problem is, sql offers no real solution to handling hierarchy&#8230; not without a little creativity that is.</p>
<p>The traditional solution is called, in geek vernacular, the adjacency model. Each category references its parent category by id or name (it helps me to think of a child&#8217;s foreign key referencing the parent&#8217;s primary key). While this is fine for smaller sets of data, it begins to slow down the server something fierce when our categories start going five, six levels deep.</p>
<p>So then what&#8217;s the solution? <a title="Managing Hierarchical Data in a Database" href="http://dev.mysql.com/tech-resources/articles/hierarchical-data.html" target="_blank">Nested sets</a>. An almost simple idea when you first hear about it, nested sets provide some many more possibilities than the adjacency model ever could. Consider the following diagram representing a simple category tree using the nested set model.</p>
<p><img src="http://dev.mysql.com/tech-resources/articles/hierarchical-data-3.png" alt="The Nested Set Model in Diagram" /></p>
<div style="color:#999;text-align:right;font-size:9px;">Image source: http://www.mysql.com</div>
<p>Every category is given a left and a right value. Look at `Electronics`. Notice how its left value is 1 and its right value is 20? The top-most category encompasses the entire tree, and all subcategories have left and right values within this range. In fact this is always the same no matter where you are in the tree; the children of a parent category are always within the parents left and right value. Look at a more traditional tree diagram.</p>
<p><img src="http://dev.mysql.com/tech-resources/articles/hierarchical-data-4.png" alt="Nested Sets Diagram in Traditional Tree Representation" /></p>
<div style="color:#999;text-align:right;font-size:9px;">Image source: http://www.mysql.com</div>
<p>Visualize a strangely mathematically-adept caterpillar starting at the top and moving to the left; it adds one at each step as it crawls all the way around.</p>
<p>&#8220;So what?&#8221; you ask. That&#8217;s the beauty of nested set simplicity. This simple fact allows for the creation of queries that can reference the relationships between our categories in a myriad of ways. And oh, is it fast in a <a title="Optimizing Your Database" href="http://www.databasejournal.com/features/mysql/article.php/1382791/Optimizing-MySQL-Queries-and-Indexes.htm" target="_blank">properly indexed database</a>. Consider the following, common, function on most websites.</p>
<h2>Breadcrumbing</h2>
<p>Here is how we might retrieve a breadcrumbing path from our current location in the tree all the way back to the top most level using the adjacency model.</p>
<pre class="brush: sql">
SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent = t1.category_id
LEFT JOIN category AS t3 ON t3.parent = t2.category_id
LEFT JOIN category AS t4 ON t4.parent = t3.category_id
WHERE t1.name = &#039;ELECTRONICS&#039; AND t4.name = &#039;FLASH&#039;;
</pre>
<p>And now here is the same result obtained with the nested set model.</p>
<pre class="brush: sql">
SELECT parent.name
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.name = &#039;FLASH&#039;
ORDER BY parent.lft;
</pre>
<p>OK, so that&#8217;s four aliased tables <a title="MySQL: The Leading Open-Source Database" href="http://www.mysql.com" target="_blank">mysql</a> has to load into memory for the adjacency model vs two for nested sets. Resources aside, the single biggest advantage of the nested set model is the management of hierarchical data;that is, deleting and adding branches or leafs (seriously, the tree analogy could not be more useful).</p>
<p>What happens to the rest of your categories&#8217; relationships to each other when our tree is pruned, or new branches are added. Are some categories left orphaned, or do they just fall of the tree entirely?</p>
<p>That is a danger in both models, but I have found nested sets to be much more useful as the technology to drive a category management system. I could give a content manager drag-and-drop functionality for placing the category where he/she pleased. Moving sub-trees around is easy and sorting a snap.</p>
<p>Hopefully I&#8217;ve given you enough to whet your appetite and you will <a title="Managing Hierarchical Data in a Database" href="http://dev.mysql.com/tech-resources/articles/hierarchical-data.html" target="_blank">continue reading about the awesomeness of nested sets</a>.</p>
<p>I run php/mysql and have found <a title="nsTrees Library" href="http://www.edutech.ch/contribution/nstrees/index.php">this class</a> to be incredibly useful. More <a title="Nested Sets for Breadcrumbs" href="http://www.developer.com/db/article.php/3517366" target="_self">here</a> and <a title="Hierarchical model" href="http://en.wikipedia.org/wiki/Hierarchical_model" target="_self">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mycrazydream.net/wp/2009/04/nested-sets-for-category-structure-in-a-mysql-database/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>

