<?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>肉包子的摇滚生活 &#187; 数据库</title>
	<atom:link href="http://www.fangyuqiang.com/archives/category/db/feed" rel="self" type="application/rss+xml" />
	<link>http://www.fangyuqiang.com</link>
	<description>在通往架构师的路上努力着...</description>
	<lastBuildDate>Mon, 14 Mar 2011 03:48:39 +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>INSERT INTO .. ON DUPLICATE KEY解决数据库备份主键冲突问题</title>
		<link>http://www.fangyuqiang.com/archives/920</link>
		<comments>http://www.fangyuqiang.com/archives/920#comments</comments>
		<pubDate>Tue, 06 Jul 2010 09:01:26 +0000</pubDate>
		<dc:creator>fangyuqiang</dc:creator>
				<category><![CDATA[数据库]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://www.fangyuqiang.com/?p=920</guid>
		<description><![CDATA[最近数据库中误操作删除了一系列数据，因为之前有备份数据库，就进行一个恢复操作，结果导入备份数据的时候发现会发生主键冲突的问题，导致导入失败。 对mysql不熟悉，原以为要设法把重复的主键全都删除，再来做导入，后来发现mysql本身是能够处理这样的问题的。就是在导入数据的时候，采用 INSERT INTO .. ON DUPLICATE KEY 如果在INSERT语句末尾指定了ON DUPLICATE KEY UPDATE，并且插入行后会导致在一个UNIQUE索引或PRIMARY KEY中出现重复值，则执行旧行UPDATE；如果不会导致唯一值列重复的问题，则插入新行。 如果你想了解更多关于INSERT INTO .. ON DUPLICATE KEY的功能说明，详见MySQL参考文档：13.2.4. INSERT语法 现在问题来了，如果INSERT多行记录， ON DUPLICATE KEY UPDATE后面字段的值怎么指定？要知道一条INSERT语句中只能有一个ON DUPLICATE KEY UPDATE，到底他会更新一行记录，还是更新所有需要更新的行。这个问题困扰了我很久了，其实使用VALUES()函数一切问题都解决了。 举个例子，字段a被定义为UNIQUE，并且原数据库表table中已存在记录(2,2,9)和(3,2,1)，如果插入记录的a值与原 有记录重复，则更新原有记录，否则插入新行： 1.INSERT INTO table (a,b,c) VALUES 2.(1,2,3), 3.(2,5,7), 4.(3,3,6), 5.(4,8,2), 6.ON DUPLICATE KEY UPDATE b=VALUES(b); 以上SQL语句的执行，发现(2,5,7)中的a与原有记录(2,2,9)发生唯一值冲突，则执行ON DUPLICATE KEY UPDATE，将原有记录(2,2,9)更新成(2,5,9)，将(3,2,1)更新成(3,3,1)，插入新记录(1,2,3)和(4,8,2) 注意：ON DUPLICATE KEY UPDATE只是MySQL的特有语法，并不是SQL标准语法！ 通过采用ON DUPLICATE KEY这样的语句，成功导入备份数据。 [...]]]></description>
			<content:encoded><![CDATA[<p>最近数据库中误操作删除了一系列数据，因为之前有备份数据库，就进行一个恢复操作，结果导入备份数据的时候发现会发生主键冲突的问题，导致导入失败。</p>
<p><span id="more-920"></span></p>
<p>对mysql不熟悉，原以为要设法把重复的主键全都删除，再来做导入，后来发现mysql本身是能够处理这样的问题的。就是在导入数据的时候，采用</p>
<p>INSERT INTO .. ON DUPLICATE KEY</p>
<blockquote><p>如果在INSERT语句末尾指定了ON DUPLICATE KEY UPDATE，并且插入行后会导致在一个UNIQUE索引或PRIMARY  KEY中出现重复值，则执行旧行UPDATE；如果不会导致唯一值列重复的问题，则插入新行。</p>
<p>如果你想了解更多关于INSERT INTO .. ON DUPLICATE KEY的功能说明，详见MySQL参考文档：<a title="INSERT语法" href="http://dev.mysql.com/doc/refman/5.1/zh/sql-syntax.html#insert">13.2.4. INSERT语法</a></p>
<hr />现在问题来了，如果INSERT多行记录， ON DUPLICATE KEY  UPDATE后面字段的值怎么指定？要知道一条INSERT语句中只能有一个ON DUPLICATE KEY  UPDATE，到底他会更新一行记录，还是更新所有需要更新的行。这个问题困扰了我很久了，其实使用VALUES()函数一切问题都解决了。</p>
<p>举个例子，字段a被定义为UNIQUE，并且原数据库表table中已存在记录(2,2,9)和(3,2,1)，如果插入记录的a值与原 有记录重复，则更新原有记录，否则插入新行：</p>
<div id="highlighter_647625">
<div>
<div><code>1.</code><code>INSERT</code> <code>INTO</code> <code>table</code> <code>(a,b,c) </code><code>VALUES</code></div>
<div><code>2.</code><code>(1,2,3),</code></div>
<div><code>3.</code><code>(2,5,7),</code></div>
<div><code>4.</code><code>(3,3,6),</code></div>
<div><code>5.</code><code>(4,8,2),</code></div>
<div><code>6.</code><code>ON</code> <code>DUPLICATE </code><code>KEY</code> <code>UPDATE</code> <code>b=</code><code>VALUES</code><code>(b);</code></div>
</div>
</div>
<p>以上SQL语句的执行，发现(2,5,7)中的a与原有记录(2,2,9)发生唯一值冲突，则执行ON DUPLICATE KEY  UPDATE，将原有记录(2,2,9)更新成(2,5,9)，将(3,2,1)更新成(3,3,1)，插入新记录(1,2,3)和(4,8,2)</p>
<p>注意：ON DUPLICATE KEY UPDATE只是MySQL的特有语法，并不是SQL标准语法！</p></blockquote>
<p>通过采用ON DUPLICATE KEY这样的语句，成功导入备份数据。</p>
<p>希望对碰到导入备份数据出现主键冲突的同学有用。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fangyuqiang.com/archives/920/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>mysql与php时间格式化参数参考</title>
		<link>http://www.fangyuqiang.com/archives/881</link>
		<comments>http://www.fangyuqiang.com/archives/881#comments</comments>
		<pubDate>Sun, 16 May 2010 15:30:17 +0000</pubDate>
		<dc:creator>fangyuqiang</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[数据库]]></category>

		<guid isPermaLink="false">http://www.fangyuqiang.com/?p=881</guid>
		<description><![CDATA[为方便查阅，从官方网站上转载的。因为mysql还有php的时间格式化参数不同，不小心会搞混，这里整理一番 PHP format character Description Example returned values Day &#8212; &#8212; d Day of the month, 2 digits with leading zeros 01 to 31 D A textual representation of a day, three letters Mon through Sun j Day of the month without leading zeros 1 to 31 l (lowercase &#8216;L&#8217;) A full textual representation of [...]]]></description>
			<content:encoded><![CDATA[<p>为方便查阅，从官方网站上转载的。因为mysql还有php的时间格式化参数不同，不小心会搞混，这里整理一番<span id="more-881"></span></p>
<h3>PHP</h3>
<table>
<thead>
<tr valign="middle">
<th><em><tt>format</tt></em> character</th>
<th>Description</th>
<th>Example returned values</th>
</tr>
</thead>
<tbody>
<tr valign="middle">
<td align="center"><em>Day</em></td>
<td align="left">&#8212;</td>
<td align="left">&#8212;</td>
</tr>
<tr valign="middle">
<td align="left"><em>d</em></td>
<td align="left">Day of the month, 2 digits with leading  zeros</td>
<td align="left"><em>01</em> to <em>31</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>D</em></td>
<td align="left">A textual representation of a day, three  letters</td>
<td align="left"><em>Mon</em> through <em>Sun</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>j</em></td>
<td align="left">Day of the month without leading zeros</td>
<td align="left"><em>1</em> to <em>31</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>l</em> (lowercase &#8216;L&#8217;)</td>
<td align="left">A full textual representation of the day of  the week</td>
<td align="left"><em>Sunday</em> through <em>Saturday</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>N</em></td>
<td align="left">ISO-8601 numeric representation of the day  of the week (added in            PHP 5.1.0)</td>
<td align="left"><em>1</em> (for Monday) through <em>7</em> (for  Sunday)</td>
</tr>
<tr valign="middle">
<td align="left"><em>S</em></td>
<td align="left">English ordinal suffix for the day of the  month, 2 characters</td>
<td align="left"><em>st</em>, <em>nd</em>, <em>rd</em> or             <em>th</em>.  Works well with <em>j</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>w</em></td>
<td align="left">Numeric representation of the day of the  week</td>
<td align="left"><em>0</em> (for Sunday) through <em>6</em> (for  Saturday)</td>
</tr>
<tr valign="middle">
<td align="left"><em>z</em></td>
<td align="left">The day of the year (starting from 0)</td>
<td align="left"><em>0</em> through <em>365</em></td>
</tr>
<tr valign="middle">
<td align="center"><em>Week</em></td>
<td align="left">&#8212;</td>
<td align="left">&#8212;</td>
</tr>
<tr valign="middle">
<td align="left"><em>W</em></td>
<td align="left">ISO-8601 week number of year, weeks starting  on Monday (added in PHP 4.1.0)</td>
<td align="left">Example: <em>42</em> (the 42nd week in the  year)</td>
</tr>
<tr valign="middle">
<td align="center"><em>Month</em></td>
<td align="left">&#8212;</td>
<td align="left">&#8212;</td>
</tr>
<tr valign="middle">
<td align="left"><em>F</em></td>
<td align="left">A full textual representation of a month,  such as January or March</td>
<td align="left"><em>January</em> through <em>December</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>m</em></td>
<td align="left">Numeric representation of a month, with  leading zeros</td>
<td align="left"><em>01</em> through <em>12</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>M</em></td>
<td align="left">A short textual representation of a month,  three letters</td>
<td align="left"><em>Jan</em> through <em>Dec</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>n</em></td>
<td align="left">Numeric representation of a month, without  leading zeros</td>
<td align="left"><em>1</em> through <em>12</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>t</em></td>
<td align="left">Number of days in the given month</td>
<td align="left"><em>28</em> through <em>31</em></td>
</tr>
<tr valign="middle">
<td align="center"><em>Year</em></td>
<td align="left">&#8212;</td>
<td align="left">&#8212;</td>
</tr>
<tr valign="middle">
<td align="left"><em>L</em></td>
<td align="left">Whether it&#8217;s a leap year</td>
<td align="left"><em>1</em> if it is a leap year, <em>0</em> otherwise.</td>
</tr>
<tr valign="middle">
<td align="left"><em>o</em></td>
<td align="left">ISO-8601 year number. This has the same  value as             <em>Y</em>, except that if the ISO week number             (<em>W</em>) belongs to the previous or next year, that year             is used instead. (added in PHP 5.1.0)</td>
<td align="left">Examples: <em>1999</em> or <em>2003</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>Y</em></td>
<td align="left">A full numeric representation of a year, 4  digits</td>
<td align="left">Examples: <em>1999</em> or <em>2003</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>y</em></td>
<td align="left">A two digit representation of a year</td>
<td align="left">Examples: <em>99</em> or <em>03</em></td>
</tr>
<tr valign="middle">
<td align="center"><em>Time</em></td>
<td align="left">&#8212;</td>
<td align="left">&#8212;</td>
</tr>
<tr valign="middle">
<td align="left"><em>a</em></td>
<td align="left">Lowercase Ante meridiem and Post meridiem</td>
<td align="left"><em>am</em> or <em>pm</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>A</em></td>
<td align="left">Uppercase Ante meridiem and Post meridiem</td>
<td align="left"><em>AM</em> or <em>PM</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>B</em></td>
<td align="left">Swatch Internet time</td>
<td align="left"><em>000</em> through <em>999</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>g</em></td>
<td align="left">12-hour format of an hour without leading  zeros</td>
<td align="left"><em>1</em> through <em>12</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>G</em></td>
<td align="left">24-hour format of an hour without leading  zeros</td>
<td align="left"><em>0</em> through <em>23</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>h</em></td>
<td align="left">12-hour format of an hour with leading zeros</td>
<td align="left"><em>01</em> through <em>12</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>H</em></td>
<td align="left">24-hour format of an hour with leading zeros</td>
<td align="left"><em>00</em> through <em>23</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>i</em></td>
<td align="left">Minutes with leading zeros</td>
<td align="left"><em>00</em> to <em>59</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>s</em></td>
<td align="left">Seconds, with leading zeros</td>
<td align="left"><em>00</em> through <em>59</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>u</em></td>
<td align="left">Microseconds (added in PHP 5.2.2)</td>
<td align="left">Example: <em>654321</em></td>
</tr>
<tr valign="middle">
<td align="center"><em>Timezone</em></td>
<td align="left">&#8212;</td>
<td align="left">&#8212;</td>
</tr>
<tr valign="middle">
<td align="left"><em>e</em></td>
<td align="left">Timezone identifier (added in PHP 5.1.0)</td>
<td align="left">Examples: <em>UTC</em>, <em>GMT</em>, <em>Atlantic/Azores</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>I</em> (capital i)</td>
<td align="left">Whether or not the date is in daylight  saving time</td>
<td align="left"><em>1</em> if Daylight Saving Time, <em>0</em> otherwise.</td>
</tr>
<tr valign="middle">
<td align="left"><em>O</em></td>
<td align="left">Difference to Greenwich time (GMT) in hours</td>
<td align="left">Example: <em>+0200</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>P</em></td>
<td align="left">Difference to Greenwich time (GMT) with  colon between hours and minutes (added in PHP 5.1.3)</td>
<td align="left">Example: <em>+02:00</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>T</em></td>
<td align="left">Timezone abbreviation</td>
<td align="left">Examples: <em>EST</em>, <em>MDT</em> &#8230;</td>
</tr>
<tr valign="middle">
<td align="left"><em>Z</em></td>
<td align="left">Timezone offset in seconds. The offset for  timezones west of UTC is always            negative, and for those east of UTC is always positive.</td>
<td align="left"><em>-43200</em> through <em>50400</em></td>
</tr>
<tr valign="middle">
<td align="center"><em>Full Date/Time</em></td>
<td align="left">&#8212;</td>
<td align="left">&#8212;</td>
</tr>
<tr valign="middle">
<td align="left"><em>c</em></td>
<td align="left">ISO 8601 date (added in PHP 5)</td>
<td align="left">2004-02-12T15:19:21+00:00</td>
</tr>
<tr valign="middle">
<td align="left"><em>r</em></td>
<td align="left"><a href="http://www.faqs.org/rfcs/rfc2822">» RFC 2822</a> formatted date</td>
<td align="left">Example: <em>Thu, 21 Dec 2000 16:01:07 +0200</em></td>
</tr>
<tr valign="middle">
<td align="left"><em>U</em></td>
<td align="left">Seconds since the Unix Epoch (January 1 1970  00:00:00 GMT)</td>
<td align="left">See also <a href="http://www.php.net/manual/en/function.time.php">time()</a></td>
</tr>
</tbody>
</table>
<p>Unrecognized characters in the format string will be printed        as-is.  The <em>Z</em> format will always return        <em>0</em> when using <a href="http://www.php.net/manual/en/function.gmdate.php">gmdate()</a>.</p>
<p><strong>Note</strong>:                  Since this function only accepts  <a href="http://www.php.net/manual/en/language.types.integer.php">integer</a> timestamps the         <em>u</em> format character is only useful when using the         <a href="http://www.php.net/manual/en/function.date-format.php">date_format()</a> function with user based  timestamps         created with <a href="http://www.php.net/manual/en/function.date-create.php">date_create()</a>.</p>
<h3>MySQL</h3>
<table>
<tbody>
<tr>
<th>Specifier</th>
<th>Description</th>
</tr>
<tr>
<td><code>%a</code></td>
<td>Abbreviated weekday name                   (<code>Sun</code>..<code>Sat</code>)</td>
</tr>
<tr>
<td><code>%b</code></td>
<td>Abbreviated month name (<code>Jan</code>..<code>Dec</code>)</td>
</tr>
<tr>
<td><code>%c</code></td>
<td>Month, numeric (<code>0</code>..<code>12</code>)</td>
</tr>
<tr>
<td><code>%D</code></td>
<td>Day of the month with English suffix (<code>0th</code>,                   <code>1st</code>, <code>2nd</code>,                   <code>3rd</code>, …)</td>
</tr>
<tr>
<td><code>%d</code></td>
<td>Day of the month, numeric (<code>00</code>..<code>31</code>)</td>
</tr>
<tr>
<td><code>%e</code></td>
<td>Day of the month, numeric (<code>0</code>..<code>31</code>)</td>
</tr>
<tr>
<td><code>%f</code></td>
<td>Microseconds (<code>000000</code>..<code>999999</code>)</td>
</tr>
<tr>
<td><code>%H</code></td>
<td>Hour (<code>00</code>..<code>23</code>)</td>
</tr>
<tr>
<td><code>%h</code></td>
<td>Hour (<code>01</code>..<code>12</code>)</td>
</tr>
<tr>
<td><code>%I</code></td>
<td>Hour (<code>01</code>..<code>12</code>)</td>
</tr>
<tr>
<td><code>%i</code></td>
<td>Minutes, numeric (<code>00</code>..<code>59</code>)</td>
</tr>
<tr>
<td><code>%j</code></td>
<td>Day of year (<code>001</code>..<code>366</code>)</td>
</tr>
<tr>
<td><code>%k</code></td>
<td>Hour (<code>0</code>..<code>23</code>)</td>
</tr>
<tr>
<td><code>%l</code></td>
<td>Hour (<code>1</code>..<code>12</code>)</td>
</tr>
<tr>
<td><code>%M</code></td>
<td>Month name (<code>January</code>..<code>December</code>)</td>
</tr>
<tr>
<td><code>%m</code></td>
<td>Month, numeric (<code>00</code>..<code>12</code>)</td>
</tr>
<tr>
<td><code>%p</code></td>
<td><code>AM</code> or <code>PM</code></td>
</tr>
<tr>
<td><code>%r</code></td>
<td>Time, 12-hour (<code>hh:mm:ss</code> followed by                   <code>AM</code> or <code>PM</code>)</td>
</tr>
<tr>
<td><code>%S</code></td>
<td>Seconds (<code>00</code>..<code>59</code>)</td>
</tr>
<tr>
<td><code>%s</code></td>
<td>Seconds (<code>00</code>..<code>59</code>)</td>
</tr>
<tr>
<td><code>%T</code></td>
<td>Time, 24-hour (<code>hh:mm:ss</code>)</td>
</tr>
<tr>
<td><code>%U</code></td>
<td>Week (<code>00</code>..<code>53</code>),  where Sunday is the                   first day of the week</td>
</tr>
<tr>
<td><code>%u</code></td>
<td>Week (<code>00</code>..<code>53</code>),  where Monday is the                   first day of the week</td>
</tr>
<tr>
<td><code>%V</code></td>
<td>Week (<code>01</code>..<code>53</code>),  where Sunday is the                   first day of the week; used with <code>%X</code></td>
</tr>
<tr>
<td><code>%v</code></td>
<td>Week (<code>01</code>..<code>53</code>),  where Monday is the                   first day of the week; used with <code>%x</code></td>
</tr>
<tr>
<td><code>%W</code></td>
<td>Weekday name (<code>Sunday</code>..<code>Saturday</code>)</td>
</tr>
<tr>
<td><code>%w</code></td>
<td>Day of the week                   (<code>0</code>=Sunday..<code>6</code>=Saturday)</td>
</tr>
<tr>
<td><code>%X</code></td>
<td>Year for the week where Sunday is the first day of the week,  numeric,                   four digits; used with <code>%V</code></td>
</tr>
<tr>
<td><code>%x</code></td>
<td>Year for the week, where Monday is the first day of the week,  numeric,                   four digits; used with <code>%v</code></td>
</tr>
<tr>
<td><code>%Y</code></td>
<td>Year, numeric, four digits</td>
</tr>
<tr>
<td><code>%y</code></td>
<td>Year, numeric (two digits)</td>
</tr>
<tr>
<td><code>%%</code></td>
<td>A literal “<code>%</code>”  character</td>
</tr>
<tr>
<td><code>%<em><code>x</code></em></code></td>
<td><em><code>x</code></em>, for any                   “<em><code>x</code></em>”  not listed                   above</td>
</tr>
</tbody>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.fangyuqiang.com/archives/881/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[译]MYSQL中分层数据的管理</title>
		<link>http://www.fangyuqiang.com/archives/382</link>
		<comments>http://www.fangyuqiang.com/archives/382#comments</comments>
		<pubDate>Tue, 21 Jul 2009 15:46:36 +0000</pubDate>
		<dc:creator>fangyuqiang</dc:creator>
				<category><![CDATA[数据库]]></category>
		<category><![CDATA[数据结构]]></category>
		<category><![CDATA[算法]]></category>

		<guid isPermaLink="false">http://www.fangyuqiang.com/?p=382</guid>
		<description><![CDATA[在看cakephp的API的时候发现的一篇介绍多级树形结构数据的管理，本来想找时间翻译的，发现已经有了翻译版本的，感谢yimin这位翻译者，可惜找不到他的链接了。]]></description>
			<content:encoded><![CDATA[<p>在看cakephp的API的时候发现的一篇介绍多级树形结构数据的管理，本来想找时间翻译的，发现已经有了翻译版本的，感谢yimin这位翻译者，可惜找不到他的链接了。</p>
<h3>MYSQL中分层数据的管理</h3>
<p>By Mike Hillyer</p>
<h3>引言</h3>
<p>大多数用户都曾在数据库中处理过分层数据(hierarchical data)，认为分层数据的管理不是关系数据库的目的。之所以这么认为，是因为关系数据库中的表没有层次关系，只是简单的平面化的列表；而分层数据具有父－子关系，显然关系数据库中的表不能自然地表现出其分层的特性。</p>
<p>我们认为，分层数据是每项只有一个父项和零个或多个子项（根项除外，根项没有父项）的数据集合。分层数据存在于许多基于数据库的应用程序中，包括论坛和邮件列表中的分类、商业组织图表、内容管理系统的分类、产品分类。我们打算使用下面一个虚构的电子商店的</p>
<p>产品分类：</p>
<p>这些分类层次与上面提到的一些例子中的分类层次是相类似的。在本文中我们将从传统的邻接表(adjacency list)模型出发，阐述2种在MySQL中处理分层数据的模型。</p>
<h3>邻接表模型</h3>
<p>上述例子的分类数据将被存储在下面的数据表中（我给出了全部的数据表创建、数据插入的代码，你可以跟着做）：</p>
<pre class="sql" title="code">CREATE TABLE category(
category_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20) NOT NULL,
parent INT DEFAULT NULL);
INSERT INTO category
VALUES(1,'ELECTRONICS',NULL),(2,'TELEVISIONS',1),(3,'TUBE',2),
(4,'LCD',2),(5,'PLASMA',2),(6,'PORTABLE ELECTRONICS',1),
(7,'MP3 PLAYERS',6),(8,'FLASH',7),
(9,'CD PLAYERS',6),(10,'2 WAY RADIOS',6);
SELECT * FROM category ORDER BY category_id;</pre>
<pre class="sql" title="code">+-------------+----------------------+--------+
| category_id | name                 | parent |
+-------------+----------------------+--------+
|           1 | ELECTRONICS          |   NULL |
|           2 | TELEVISIONS           |      1 |
|           3 | TUBE                     |      2 |
|           4 | LCD                       |      2 |
|           5 | PLASMA                 |      2 |
|           6 | PORTABLE ELECTRONICS |      1 |
|           7 | MP3 PLAYERS          |      6 |
|           8 | FLASH                |      7 |
|           9 | CD PLAYERS           |      6 |
|          10 | 2 WAY RADIOS         |      6 |
+-------------+----------------------+--------+
10 rows in set (0.00 sec)</pre>
<p>在邻接表模型中，数据表中的每项包含了指向其父项的指示器。在此例中，最上层项的父项为空值(NULL)。邻接表模型的优势在于它很简单，可以很容易地看出FLASH是MP3 PLAYERS的子项，哪个是portable electronics的子项，哪个是electronics的子项。虽然，在客户端编码中邻接表模型处理起来也相当的简单，但是如果是纯SQL编码的话，该模型会有很多问题。</p>
<h3>检索整树</h3>
<p>通常在处理分层数据时首要的任务是，以某种缩进形式来呈现一棵完整的树。为此，在纯SQL编码中通常的做法是使用自连接(self-join)：</p>
<pre class="sql" title="code">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 = 'ELECTRONICS';

+-------------+----------------------+--------------+-------+
| lev1        | lev2                 | lev3         | lev4  |
+-------------+----------------------+--------------+-------+
| ELECTRONICS | TELEVISIONS          | TUBE         | NULL  |
| ELECTRONICS | TELEVISIONS          | LCD          | NULL  |
| ELECTRONICS | TELEVISIONS          | PLASMA       | NULL  |
| ELECTRONICS | PORTABLE ELECTRONICS | MP3 PLAYERS  | FLASH |
| ELECTRONICS | PORTABLE ELECTRONICS | CD PLAYERS   | NULL  |
| ELECTRONICS | PORTABLE ELECTRONICS | 2 WAY RADIOS | NULL  |
+-------------+----------------------+--------------+-------+
6 rows in set (0.00 sec)</pre>
<h3>检索所有叶子节点</h3>
<p>我们可以用左连接(LEFT JOIN)来检索出树中所有叶子节点(没有孩子节点的节点）：</p>
<pre class="sql" title="code">SELECT t1.name FROM
category AS t1 LEFT JOIN category as t2
ON t1.category_id = t2.parent
WHERE t2.category_id IS NULL;
+--------------+
| name         |
+--------------+
| TUBE         |
| LCD          |
| PLASMA       |
| FLASH        |
| CD PLAYERS   |
| 2 WAY RADIOS |
+--------------+</pre>
<h3>检索单一路径</h3>
<p>通过自连接，我们也可以检索出单一路径：</p>
<pre class="sql" title="code">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 = 'ELECTRONICS' AND t4.name = 'FLASH';
+-------------+----------------------+-------------+-------+
| lev1        | lev2                 | lev3        | lev4  |
+-------------+----------------------+-------------+-------+
| ELECTRONICS | PORTABLE ELECTRONICS | MP3 PLAYERS | FLASH |
+-------------+----------------------+-------------+-------+
1 row in set (0.01 sec)</pre>
<p>这种方法的主要局限是你需要为每层数据添加一个自连接，随着层次的增加，自连接变得越来越复杂，检索的性能自然而然的也就下降了。</p>
<h3>邻接表模型的局限性</h3>
<p>用纯SQL编码实现邻接表模型有一定的难度。在我们检索某分类的路径之前，我们需要知道该分类所在的层次。另外，我们在删除节点的时候要特别小心，因为潜在的可能会孤立一棵子树（当删除portable electronics分类时，所有他的子分类都成了孤儿）。部分局限性可以通过使用客户端代码或者存储过程来解决，我们可以从树的底部开始向上迭代来获得一颗树或者单一路径，我们也可以在删除节点的时候使其子节点指向一个新的父节点，来防止孤立子树的产生。</p>
<h3>嵌套集合(Nested Set)模型</h3>
<p>我想在这篇文章中重点阐述一种不同的方法，俗称为嵌套集合模型。在嵌套集合模型中，我们将以一种新的方式来看待我们的分层数据，不再是线与点了，而是嵌套容器。我试着以嵌套容器的方式画出了electronics分类图：</p>
<p>从上图可以看出我们依旧保持了数据的层次，父分类包围了其子分类。在数据表中，我们通过使用表示节点的嵌套关系的左值(left value)和右值(right value)来表现嵌套集合模型中数据的分层特性：</p>
<pre class="sql" title="code">CREATE TABLE nested_category (
category_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20) NOT NULL,
lft INT NOT NULL,
rgt INT NOT NULL
);
INSERT INTO nested_category
VALUES(1,'ELECTRONICS',1,20),(2,'TELEVISIONS',2,9),(3,'TUBE',3,4),
(4,'LCD',5,6),(5,'PLASMA',7,8),(6,'PORTABLE ELECTRONICS',10,19),
(7,'MP3 PLAYERS',11,14),(8,'FLASH',12,13),
(9,'CD PLAYERS',15,16),(10,'2 WAY RADIOS',17,18);
SELECT * FROM nested_category ORDER BY category_id;
+-------------+----------------------+-----+-----+
| category_id | name                 | lft | rgt |
+-------------+----------------------+-----+-----+
|           1 | ELECTRONICS          |   1 |  20 |
|           2 | TELEVISIONS          |   2 |   9 |
|           3 | TUBE                 |   3 |   4 |
|           4 | LCD                  |   5 |   6 |
|           5 | PLASMA               |   7 |   8 |
|           6 | PORTABLE ELECTRONICS |  10 |  19 |
|           7 | MP3 PLAYERS          |  11 |  14 |
|           8 | FLASH                |  12 |  13 |
|           9 | CD PLAYERS           |  15 |  16 |
|          10 | 2 WAY RADIOS         |  17 |  18 |
+-------------+----------------------+-----+-----+</pre>
<p>我们使用了lft和rgt来代替left和right，是因为在MySQL中left和right是保留字。http://dev.mysql.com/doc/mysql/en/reserved-words.html，有一份详细的MySQL保留字清单。那么，我们怎样决定左值和右值呢？我们从外层节点的最左侧开始，从左到右编号：</p>
<p>这样的编号方式也同样适用于典型的树状结构：</p>
<p>当我们为树状的结构编号时，我们从左到右，一次一层，为节点赋右值前先从左到右遍历其子节点给其子节点赋左右值。这种方法被称作改进的先序遍历算法。</p>
<h3>检索整树</h3>
<p>我们可以通过自连接把父节点连接到子节点上来检索整树，是因为子节点的lft值总是在其父节点的lft值和rgt值之间：</p>
<pre class="sql" title="code">SELECT node.name
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND parent.name = 'ELECTRONICS'
ORDER BY node.lft;
+----------------------+
| name                 |
+----------------------+
| ELECTRONICS          |
| TELEVISIONS          |
| TUBE                 |
| LCD                  |
| PLASMA               |
| PORTABLE ELECTRONICS |
| MP3 PLAYERS          |
| FLASH                |
| CD PLAYERS           |
| 2 WAY RADIOS         |
+----------------------+</pre>
<p>不像先前邻接表模型的例子，这个查询语句不管树的层次有多深都能很好的工作。在BETWEEN的子句中我们没有去关心node的rgt值，是因为使用node的rgt值得出的父节点总是和使用lft值得出的是相同的。</p>
<h3>检索所有叶子节点</h3>
<p>检索出所有的叶子节点，使用嵌套集合模型的方法比邻接表模型的LEFT JOIN方法简单多了。如果你仔细得看了nested_category表，你可能已经注意到叶子节点的左右值是连续的。要检索出叶子节点，我们只要查找满足rgt=lft+1的节点：</p>
<pre class="sql" title="code">SELECT name
FROM nested_category
WHERE rgt = lft + 1;
+--------------+
| name         |
+--------------+
| TUBE         |
| LCD          |
| PLASMA       |
| FLASH        |
| CD PLAYERS   |
| 2 WAY RADIOS |
+--------------+</pre>
<h3>检索单一路径</h3>
<p>在嵌套集合模型中，我们可以不用多个自连接就可以检索出单一路径：</p>
<pre class="sql" title="code">SELECT parent.name
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.name = 'FLASH'
ORDER BY node.lft;
+----------------------+
| name                 |
+----------------------+
| ELECTRONICS          |
| PORTABLE ELECTRONICS |
| MP3 PLAYERS          |
| FLASH                |
+----------------------+</pre>
<h3>检索节点的深度</h3>
<p>我们已经知道怎样去呈现一棵整树，但是为了更好的标识出节点在树中所处层次，我们怎样才能检索出节点在树中的深度呢？我们可以在先前的查询语句上增加COUNT函数和GROUP BY子句来实现：</p>
<pre class="sql" title="code">SELECT node.name, (COUNT(parent.name) 1)
AS depth
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.name
ORDER BY node.lft;
+----------------------+-------+
| name                 | depth |
+----------------------+-------+
| ELECTRONICS          |     0 |
| TELEVISIONS          |     1 |
| TUBE                 |     2 |
| LCD                  |     2 |
| PLASMA               |     2 |
| PORTABLE ELECTRONICS |     1 |
| MP3 PLAYERS          |     2 |
| FLASH                |     3 |
| CD PLAYERS           |     2 |
| 2 WAY RADIOS         |     2 |
+----------------------+-------+</pre>
<p>我们可以根据depth值来缩进分类名字，使用CONCAT和REPEAT字符串函数1：</p>
<pre class="sql" title="code">SELECT CONCAT( REPEAT(' ', COUNT(parent.name) 1),
node.name) AS name
FROM nested_category AS node,
nested_category AS paren
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.name
ORDER BY node.lft;
+-----------------------+
| name                  |
+-----------------------+
| ELECTRONICS           |
|  TELEVISIONS          |
|   TUBE                |
|   LCD                 |
|   PLASMA              |
|  PORTABLE ELECTRONICS |
|   MP3 PLAYERS         |
|    FLASH              |
|   CD PLAYERS          |
|   2 WAY RADIOS        |
+-----------------------+</pre>
<p>当然，在客户端应用程序中你可能会用depth值来直接展示数据的层次。Web开发者会遍历该树，随着depth值的增加和减少来添加和标签。</p>
<h3>检索子树的深度</h3>
<p>当我们需要子树的深度信息时，我们不能限制自连接中的node或parent，因为这么做会打乱数据集的顺序。因此，我们添加了第三个自连接作为子查询，来得出子树新起点的深度值：</p>
<pre class="sql" title="code">SELECT node.name, (COUNT(parent.name) (
sub_tree.depth + 1)) AS depth
FROM nested_category AS node,
nested_category AS parent,
nested_category AS sub_parent,
(
SELECT node.name, (COUNT(parent.name) 1)
AS depth
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.name = 'PORTABLE ELECTRONICS'
GROUP BY node.name
ORDER BY node.lft
)AS sub_tree
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
AND sub_parent.name = sub_tree.name
GROUP BY node.name
ORDER BY node.lft;
+----------------------+-------+
| name                 | depth |
+----------------------+-------+
| PORTABLE ELECTRONICS |     0 |
| MP3 PLAYERS          |     1 |
| FLASH                |     2 |
| CD PLAYERS           |     1 |
| 2 WAY RADIOS         |     1 |
+----------------------+-------+</pre>
<p>这个查询语句可以检索出任一节点子树的深度值，包括根节点。这里的深度值跟你指定的节点有关。</p>
<h3>检索节点的直接子节点</h3>
<p>可以想象一下，你在零售网站上呈现电子产品的分类。当用户点击分类后，你将要呈现该分类下的产品，同时也需列出该分类下的直接子分类，而不是该分类下的全部分类。为此，我们只呈现该节点及其直接子节点，不再呈现更深层次的节点。例如，当呈现PORTABLE ELECTRONICS分类时，我们同时只呈现MP3 PLAYERS、CD PLAYERS和2 WAY RADIOS分类，而不呈现FLASH分类。要实现它非常的简单，在先前的查询语句上添加HAVING子句：</p>
<pre class="sql" title="code">SELECT node.name, (COUNT(parent.name) (
sub_tree.depth + 1)) AS depth
FROM nested_category AS node,
nested_category AS parent,
nested_category AS sub_parent,
(
SELECT node.name, (COUNT(parent.name) 1)
AS depth
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.name = 'PORTABLE ELECTRONICS'
GROUP BY node.name
ORDER BY node.lft
)AS sub_tree
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
AND sub_parent.name = sub_tree.name
GROUP BY node.name
HAVING depth &lt;= 1
ORDER BY node.lft;
+----------------------+-------+
| name                 | depth |
+----------------------+-------+
| PORTABLE ELECTRONICS |     0 |
| MP3 PLAYERS          |     1 |
| CD PLAYERS           |     1 |
| 2 WAY RADIOS         |     1 |
+----------------------+-------+</pre>
<p>如果你不希望呈现父节点，你可以更改HAVING depth &lt;= 1为HAVING depth = 1。</p>
<h3>嵌套集合模型中集合函数的应用</h3>
<p>让我们添加一个产品表，我们可以使用它来示例集合函数的应用：</p>
<pre class="sql" title="code">CREATE TABLE product(
product_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(40),
category_id INT NOT NULL
);
INSERT INTO product(name, category_id) VALUES('20" TV',3),('36" TV',3),
('SuperLCD
42"',4),('UltraPlasma
62"',5),('Value Plasma 38"',5),
('PowerMP3
5gb',7),('SuperPlayer
1gb',8),('Porta CD',9),('CD To go!',9),
('Family Talk 360',10);
SELECT * FROM product;
+------------+-------------------+-------------+
| product_id | name              | category_id |
+------------+-------------------+-------------+
|          1 | 20" TV            |           3 |
|          2 | 36" TV            |           3 |
|          3 | Super-LCD 42"     |           4 |
|          4 | Ultra-Plasma 62"  |           5 |
|          5 | Value Plasma 38"  |           5 |
|          6 | Power-MP3 128mb   |           7 |
|          7 | Super-Shuffle 1gb |           8 |
|          8 | Porta CD          |           9 |
|          9 | CD To go!         |           9 |
|         10 | Family Talk 360   |          10 |
+------------+-------------------+-------------+</pre>
<p>现在，让我们写一个查询语句，在检索分类树的同时，计算出各分类下的产品数量：</p>
<pre class="sql" title="code">SELECT parent.name, COUNT(product.name)
FROM nested_category AS node ,
nested_category AS parent,
product
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.category_id = product.category_id
GROUP BY parent.name
ORDER BY node.lft;
+----------------------+---------------------+
| name                 | COUNT(product.name) |
+----------------------+---------------------+
| ELECTRONICS          |                  10 |
| TELEVISIONS          |                   5 |
| TUBE                 |                   2 |
| LCD                  |                   1 |
| PLASMA               |                   2 |
| PORTABLE ELECTRONICS |                   5 |
| MP3 PLAYERS          |                   2 |
| FLASH                |                   1 |
| CD PLAYERS           |                   2 |
| 2 WAY RADIOS         |                   1 |
+----------------------+---------------------+</pre>
<p>这条查询语句在检索整树的查询语句上增加了COUNT和GROUP BY子句，同时在WHERE子句中引用了product表和一个自连接。</p>
<h3>新增节点</h3>
<p>到现在，我们已经知道了如何去查询我们的树，是时候去关注一下如何增加一个新节点来更新我们的树了。让我们再一次观察一下我们的嵌套集合图：</p>
<p>当我们想要在TELEVISIONS和PORTABLE ELECTRONICS节点之间新增一个节点，新节点的lft和rgt 的 值为10和11，所有该节点的右边节点的lft和rgt值都将加2，之后我们再添加新节点并赋相应的lft和rgt值。在MySQL 5中可以使用存储过程来完成，我假设当前大部分读者使用的是MySQL 4.1版本，因为这是最新的稳定版本。所以，我使用了锁表（LOCK TABLES）语句来隔离查询：</p>
<pre class="sql" title="code">LOCK TABLE nested_category WRITE;
SELECT @myRight := rgt FROM nested_category
WHERE name = 'TELEVISIONS';
UPDATE nested_category SET rgt = rgt + 2 WHERE rgt &gt; @myRight;
UPDATE nested_category SET lft = lft + 2 WHERE lft &gt; @myRight;
INSERT INTO nested_category(name, lft, rgt) VALUES('GAME CONSOLES', @myRight + 1,
@myRight + 2);
UNLOCK TABLES;</pre>
<p>我们可以检验一下新节点插入的正确性：</p>
<pre class="sql" title="code">SELECT CONCAT( REPEAT( ' ', (COUNT(parent.name) 1)
), node.name) AS name
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.name
ORDER BY node.lft;
+-----------------------+
| name                  |
+-----------------------+
| ELECTRONICS           |
|  TELEVISIONS          |
|   TUBE                |
|   LCD                 |
|   PLASMA              |
|  GAME CONSOLES        |
|  PORTABLE ELECTRONICS |
|   MP3 PLAYERS         |
|    FLASH              |
|   CD PLAYERS          |
|   2 WAY RADIOS        |
+-----------------------+</pre>
<p>如果我们想要在叶子节点下增加节点，我们得稍微修改一下查询语句。让我们在2 WAY RADIOS叶子节点下添加FRS节点吧：</p>
<pre class="sql" title="code">LOCK TABLE nested_category WRITE;
SELECT @myLeft := lft FROM nested_category
WHERE name = '2 WAY RADIOS';
UPDATE nested_category SET rgt = rgt + 2 WHERE rgt &gt; @myLeft;
UPDATE nested_category SET lft = lft + 2 WHERE lft &gt; @myLeft;
INSERT INTO nested_category(name, lft, rgt) VALUES('FRS', @myLeft + 1, @myLeft +
2);
UNLOCK TABLES;</pre>
<p>在这个例子中，我们扩大了新产生的父节点(2 WAY RADIOS节点）的右值及其所有它的右边节点的左右值，之后置新增节点于新父节点之下。正如你所看到的，我们新增的节点已经完全融入了嵌套集合中：</p>
<pre class="sql" title="code">SELECT CONCAT( REPEAT( ' ', (COUNT(parent.name) 1)
), node.name) AS name
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.name
ORDER BY node.lft;
+-----------------------+
| name                  |
+-----------------------+
| ELECTRONICS           |
|  TELEVISIONS          |
|   TUBE                |
|   LCD                 |
|   PLASMA              |
|  GAME CONSOLES        |
|  PORTABLE ELECTRONICS |
|   MP3 PLAYERS         |
|    FLASH              |
|   CD PLAYERS          |
|   2 WAY RADIOS        |
|    FRS                |
+-----------------------+</pre>
<h3>删除节点</h3>
<p>最后还有个基础任务，删除节点。删除节点的处理过程跟节点在分层数据中所处的位置有关，删除一个叶子节点比删除一个子节点要简单得多，因为删除子节点的时候，我们需要去处理孤立节点。删除一个叶子节点的过程正好是新增一个叶子节点的逆过程，我们在删除节点的同时该节点右边所有节点的左右值和该父节点的右值都会减去该节点的宽度值2：</p>
<pre class="sql" title="code">LOCK TABLE nested_category WRITE;
SELECT @myLeft := lft, @myRight := rgt, @myWidth := rgt lft
+ 1
FROM nested_category
WHERE name = 'GAME CONSOLES';
DELETE FROM nested_category WHERE lft BETWEEN @myLeft AND @myRight;
UPDATE nested_category SET rgt = rgt @
myWidth WHERE rgt &gt; @myRight;
UPDATE nested_category SET lft = lft @
myWidth WHERE lft &gt; @myRight;
UNLOCK TABLES;</pre>
<p>我们再一次检验一下节点已经成功删除,而且没有打乱数据的层次：</p>
<pre class="sql" title="code">SELECT CONCAT( REPEAT( ' ', (COUNT(parent.name) 1)
), node.name) AS name
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.name
ORDER BY node.lft;
+-----------------------+
| name                  |
+-----------------------+
| ELECTRONICS           |
|  TELEVISIONS          |
|   TUBE                |
|   LCD                 |
|   PLASMA              |
|  PORTABLE ELECTRONICS |
|   MP3 PLAYERS         |
|    FLASH              |
|   CD PLAYERS          |
|   2 WAY RADIOS        |
|    FRS                |
+-----------------------+</pre>
<p>这个方法可以完美地删除节点及其子节点：</p>
<pre class="sql" title="code">LOCK TABLE nested_category WRITE;
SELECT @myLeft := lft, @myRight := rgt, @myWidth := rgt lft
+ 1
FROM nested_category</pre>
<p>2 [译注] 作者的本意是举删除叶子节点的情况，不过他给出的查询语句是通用型的，删除节点及其子节点，跟下例的查询语句是相同的。</p>
<pre class="sql" title="code">WHERE name = 'MP3 PLAYERS';
DELETE FROM nested_category WHERE lft BETWEEN @myLeft AND @myRight;
UPDATE nested_category SET rgt = rgt @
myWidth WHERE rgt &gt; @myRight;
UPDATE nested_category SET lft = lft @
myWidth WHERE lft &gt; @myRight;
UNLOCK TABLES;</pre>
<p>再次验证我们已经成功的删除了一棵子树：</p>
<pre class="sql" title="code">SELECT CONCAT( REPEAT( ' ', (COUNT(parent.name) 1)
), node.name) AS name
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.name
ORDER BY node.lft;
+-----------------------+
| name                  |
+-----------------------+
| ELECTRONICS           |
|  TELEVISIONS          |
|   TUBE                |
|   LCD                 |
|   PLASMA              |
|  PORTABLE ELECTRONICS |
|   CD PLAYERS          |
|   2 WAY RADIOS        |
|    FRS                |
+-----------------------+</pre>
<p>有时，我们只删除该节点，而不删除该节点的子节点。在一些情况下，你希望改变其名字为占位符，直到替代名字的出现，比如你开除了一个主管（需要更换主管）。在另外一些情况下，你希望子节点挂到该删除节点的父节点下：</p>
<pre class="sql" title="code">LOCK TABLE nested_category WRITE;
SELECT @myLeft := lft, @myRight := rgt, @myWidth := rgt lft
+ 1
FROM nested_category
WHERE name = 'PORTABLE ELECTRONICS';
DELETE FROM nested_category WHERE lft = @myLeft;
UPDATE nested_category SET rgt = rgt 1,
lft = lft 1
WHERE lft BETWEEN @myLeft
AND @myRight;
UPDATE nested_category SET rgt = rgt 2
WHERE rgt &gt; @myRight;
UPDATE nested_category SET lft = lft 2
WHERE lft &gt; @myRight;
UNLOCK TABLES;</pre>
<p>在这个例子中，我们对该节点所有右边节点的左右值都减去了2（因为不考虑其子节点，该节点的宽度为2），对该节点的子节点的左右值都减去了1（弥补由于失去父节点的左值造成的裂缝）。我们再一次确认，那些节点是否都晋升了：</p>
<pre class="sql" title="code">SELECT CONCAT( REPEAT( ' ', (COUNT(parent.name) 1)
), node.name) AS name
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.name
ORDER BY node.lft;
+---------------+
| name          |
+---------------+
| ELECTRONICS   |
|  TELEVISIONS  |
|   TUBE        |
|   LCD         |
|   PLASMA      |
|  CD PLAYERS   |
|  2 WAY RADIOS |
|   FRS         |
+---------------+</pre>
<p>有时，当删除节点的时候，把该节点的一个子节点挂载到该节点的父节点下，而其他节点挂到该节点父节点的兄弟节点下，考虑到篇幅这种情况不在这里解说了。</p>
<h3>最后的思考</h3>
<p>我希望这篇文章对你有所帮助，SQL中的嵌套集合的观念大约有十年的历史了，在网上和一些书中都能找到许多相关信息。在我看来，讲述分层数据的管理最全面的，是来自一本名叫《Joe Celko&#8217;s Trees and Hierarchies in SQL for Smarties》3的书，此书的作者是在高</p>
<p>级SQL领域倍受尊敬的Joe Celko。Joe Celko被认为是嵌套集合模型的创造者，更是该领域内的多产作家。我把Celko的书当作无价之宝，并极力地推荐它。在这本书中涵盖了在此文中没有提及的一些高级话题，也提到了其他一些关于邻接表和嵌套集合模型下管理分层数据的方法。</p>
<p>在随后的参考书目章节中4，我列出了一些网络资源，也许对你研究分层数据的管理会有所帮助，其中包括一些PHP相关的资源（处理嵌套集合的PHP库）。如果你还在使用邻接表模型，你该去试试嵌套集合模型了，在Storing Hierarchical Data in a Databas e5 文中下方列出的一些资源链接中能找到一些样例代码，可以去试验一下。</p>
<h3>关于作者/译者</h3>
<p>Mike Hillyer，本文的作者，MySQL Ab的技术作家，生活在加拿大的阿尔伯达省6 。</p>
<p>Yimin，本文的译者，就读于浙江理工大学计算机系。我的Blog：http://liyimin.net/blog</p>
<p>6 [译注]加拿大西部一省份，位于不列颠哥伦比亚省和萨斯喀彻温省之间。于1905年加入联邦。在六十年代初发现石油和天然气以前，小麦种植和养牛业为该省经济的主要支柱。埃德蒙顿为该省首府及最大的城市。人口2,237,724</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fangyuqiang.com/archives/382/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

