﻿<?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>奋斗足迹&#124;崔玉松 &#187; MySQL</title>
	<atom:link href="http://fendou.org/tag/mysql/feed/" rel="self" type="application/rss+xml" />
	<link>http://fendou.org</link>
	<description>为家人，为自己，为生活~~</description>
	<lastBuildDate>Tue, 17 Jan 2012 03:45:57 +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>Mysql中union和order by的问题及优先级</title>
		<link>http://fendou.org/2011/11/16/mysql-union-order-by-problem/</link>
		<comments>http://fendou.org/2011/11/16/mysql-union-order-by-problem/#comments</comments>
		<pubDate>Wed, 16 Nov 2011 07:03:10 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Excellence Article]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=854</guid>
		<description><![CDATA[在Mysql的参考手册中，并没有对union和order by的优先级进行说明 它建议的方法是，对SQL语句加上（），这样能使SQL的语义更清晰 例如，需要对union后的结果进行order by，则： &#40;SELECT a FROM tbl_name WHERE a=10 AND B=1&#41; UNION &#40;SELECT a FROM tbl_name WHERE a=11 AND B=2&#41; ORDER BY a LIMIT 10； 如果，需要对单个SQL语句进行order by，则应把order by子句放入圆括号中，如下： &#40;SELECT a FROM tbl_name WHERE a=10 AND B=1 ORDER BY &#8230; <a href="http://fendou.org/2011/11/16/mysql-union-order-by-problem/">继续阅读 <span class="meta-nav">&#8594;</span></a><table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2010%2F05%2F28%2Fphp-mysql-procedure%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F16%2Fmysql-union-order-by-problem%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">PHP中操作mysql执行存储过程</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2009%2F01%2F20%2Fmysql-heap%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F16%2Fmysql-union-order-by-problem%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">mysql内存表heap使用总结</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2011%2F05%2F06%2Fmysql-communication-protocols%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F16%2Fmysql-union-order-by-problem%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL通信协议</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2010%2F03%2F07%2Fmysql-view%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F16%2Fmysql-union-order-by-problem%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL视图介绍</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2009%2F07%2F05%2Fmysql-index-limit%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F16%2Fmysql-union-order-by-problem%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL中索引限制</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p> 在Mysql的参考手册中，并没有对union和order by的优先级进行说明<br />
它建议的方法是，对SQL语句加上（），这样能使SQL的语义更清晰<br />
例如，需要对union后的结果进行order by，则：</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #993333; font-weight: bold;">SELECT</span> a <span style="color: #993333; font-weight: bold;">FROM</span> tbl_name <span style="color: #993333; font-weight: bold;">WHERE</span> a<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">10</span> <span style="color: #993333; font-weight: bold;">AND</span> B<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>  
<span style="color: #993333; font-weight: bold;">UNION</span>  
<span style="color: #66cc66;">&#40;</span><span style="color: #993333; font-weight: bold;">SELECT</span> a <span style="color: #993333; font-weight: bold;">FROM</span> tbl_name <span style="color: #993333; font-weight: bold;">WHERE</span> a<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">11</span> <span style="color: #993333; font-weight: bold;">AND</span> B<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span>  
<span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> a <span style="color: #993333; font-weight: bold;">LIMIT</span> <span style="color: #cc66cc;">10</span>；</pre></div></div>

<p>如果，需要对单个SQL语句进行order by，则应把order by子句放入圆括号中，如下：</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #66cc66;">&#40;</span><span style="color: #993333; font-weight: bold;">SELECT</span> a <span style="color: #993333; font-weight: bold;">FROM</span> tbl_name <span style="color: #993333; font-weight: bold;">WHERE</span> a<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">10</span> <span style="color: #993333; font-weight: bold;">AND</span> B<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">1</span> <span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> a <span style="color: #993333; font-weight: bold;">LIMIT</span> <span style="color: #cc66cc;">10</span><span style="color: #66cc66;">&#41;</span>  
<span style="color: #993333; font-weight: bold;">UNION</span>  
<span style="color: #66cc66;">&#40;</span><span style="color: #993333; font-weight: bold;">SELECT</span> a <span style="color: #993333; font-weight: bold;">FROM</span> tbl_name <span style="color: #993333; font-weight: bold;">WHERE</span> a<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">11</span> <span style="color: #993333; font-weight: bold;">AND</span> B<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">2</span> <span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> a <span style="color: #993333; font-weight: bold;">LIMIT</span> <span style="color: #cc66cc;">10</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>另外注意：圆括号中用于单个SQL语句的ORDER BY只有当与LIMIT结合后，才起作用。否则，ORDER BY被优化去除。<br />
我在innodb引擎的2个表上测试了没有加()，进行union和order by的操作，如下：</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> a <span style="color: #993333; font-weight: bold;">FROM</span> tbl_name <span style="color: #993333; font-weight: bold;">WHERE</span> a<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">10</span> <span style="color: #993333; font-weight: bold;">AND</span> B<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">1</span>  
<span style="color: #993333; font-weight: bold;">UNION</span>  
<span style="color: #993333; font-weight: bold;">SELECT</span> a <span style="color: #993333; font-weight: bold;">FROM</span> tbl_name <span style="color: #993333; font-weight: bold;">WHERE</span> a<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">11</span> <span style="color: #993333; font-weight: bold;">AND</span> B<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">2</span>  
<span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> a <span style="color: #993333; font-weight: bold;">LIMIT</span> <span style="color: #cc66cc;">10</span>;</pre></div></div>

<p>发现，它默认的结果也是先进行union，然后再order by，和第一种情况执行结果相同<br />
不过，为了逻辑清晰，最好还是加上对应的()比较好<br />
另外：Mysql中union可以有union，union distinct，union all这3中形式<br />
union和union distinct会对union后的结果进行排重，保证所有返回的行都是唯一的<br />
union all则会返回所有SELECT语句中得到所有匹配的行</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2010%2F05%2F28%2Fphp-mysql-procedure%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F16%2Fmysql-union-order-by-problem%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">PHP中操作mysql执行存储过程</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2009%2F01%2F20%2Fmysql-heap%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F16%2Fmysql-union-order-by-problem%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">mysql内存表heap使用总结</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2011%2F05%2F06%2Fmysql-communication-protocols%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F16%2Fmysql-union-order-by-problem%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL通信协议</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2010%2F03%2F07%2Fmysql-view%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F16%2Fmysql-union-order-by-problem%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL视图介绍</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2009%2F07%2F05%2Fmysql-index-limit%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F16%2Fmysql-union-order-by-problem%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL中索引限制</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/11/16/mysql-union-order-by-problem/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>MySQL写入优化</title>
		<link>http://fendou.org/2011/08/30/mysql%e5%86%99%e5%85%a5%e4%bc%98%e5%8c%96/</link>
		<comments>http://fendou.org/2011/08/30/mysql%e5%86%99%e5%85%a5%e4%bc%98%e5%8c%96/#comments</comments>
		<pubDate>Tue, 30 Aug 2011 15:03:14 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Excellence Article]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=846</guid>
		<description><![CDATA[innodb_buffer_pool_size 如果用Innodb，那么这是一个重要变量。相对于MyISAM来说，Innodb对于buffer size更敏感。MySIAM可能对于大数据量使用默认的key_buffer_size也还好，但Innodb在大数据量时用默认值就感觉在爬了。 Innodb的缓冲池会缓存数据和索引，所以不需要给系统的缓存留空间，如果只用Innodb，可以把这个值设为内存的70%-80%。和 key_buffer相同，如果数据量比较小也不怎么增加，那么不要把这个值设太高也可以提高内存的使用率。 innodb_additional_pool_size 这个的效果不是很明显，至少是当操作系统能合理分配内存时。但你可能仍需要设成20M或更多一点以看Innodb会分配多少内存做其他用途。 innodb_log_file_size 对于写很多尤其是大数据量时非常重要。要注意，大的文件提供更高的性能，但数据库恢复时会用更多的时间。我一般用64M-512M，具体取决于服务器的空间。 innodb_log_buffer_size 默认值对于多数中等写操作和事务短的运用都是可以的。如果经常做更新或者使用了很多blob数据，应该增大这个值。但太大了也是浪费内存，因为1秒钟总会 flush（这个词的中文怎么说呢？）一次，所以不需要设到超过1秒的需求。8M-16M一般应该够了。小的运用可以设更小一点。 innodb_flush_log_at_trx_commit （这个很管用） 抱怨Innodb比MyISAM慢 100倍？那么你大概是忘了调整这个值。默认值1的意思是每一次事务提交或事务外的指令都需要把日志写入（flush）硬盘，这是很费时的。特别是使用电 池供电缓存（Battery backed up cache）时。设成2对于很多运用，特别是从MyISAM表转过来的是可以的，它的意思是不写入硬盘而是写入系统缓存。日志仍然会每秒flush到硬 盘，所以你一般不会丢失超过1-2秒的更新。设成0会更快一点，但安全方面比较差，即使MySQL挂了也可能会丢失事务的数据。而值2只会在整个操作系统 挂了时才可能丢数据。 上面是网上看的，我发现慢查询日志内有很多update和insert的查询，就把innodb_flush_log_at_trx_commit改成了2，效果很明显，改成0会更明显，但安全性比较差。做下面的操作启动mysqld就生效： vim /etc/my.cnf innodb_flush_log_at_trx_commit=2 也可以在mysqld运行时执行： set GLOBAL innodb_flush_log_at_trx_commit = 2 下面是mysql手册上innodb_flush_log_at_trx_commit的解释： 如果innodb_flush_log_at_trx_commit设置为0，log buffer将每秒一次地写入log file中，并且log file的flush(刷到磁盘)操作同时进行；但是，这种模式下，在事务提交的时候，不会有任何动作。如果 innodb_flush_log_at_trx_commit设置为1(默认值)，log buffer每次事务提交都会写入log file，并且，flush刷到磁盘中去。如果innodb_flush_log_at_trx_commit设置为2，log &#8230; <a href="http://fendou.org/2011/08/30/mysql%e5%86%99%e5%85%a5%e4%bc%98%e5%8c%96/">继续阅读 <span class="meta-nav">&#8594;</span></a><table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2010%2F03%2F07%2Fmysql-view%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql%25E5%2586%2599%25E5%2585%25A5%25E4%25BC%2598%25E5%258C%2596%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL视图介绍</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2011%2F05%2F06%2Fmysql-5-1-56-innodb-plugin%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql%25E5%2586%2599%25E5%2585%25A5%25E4%25BC%2598%25E5%258C%2596%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL 5.1.56 使用 InnoDB Plugin</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2010%2F03%2F07%2Fmysql-root-lose%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql%25E5%2586%2599%25E5%2585%25A5%25E4%25BC%2598%25E5%258C%2596%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">mysql root帐号丢失解决办法</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2010%2F05%2F28%2Fphp-mysql-procedure%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql%25E5%2586%2599%25E5%2585%25A5%25E4%25BC%2598%25E5%258C%2596%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">PHP中操作mysql执行存储过程</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2011%2F11%2F16%2Fmysql-union-order-by-problem%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql%25E5%2586%2599%25E5%2585%25A5%25E4%25BC%2598%25E5%258C%2596%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Mysql中union和order by的问题及优先级</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p><strong>innodb_buffer_pool_size</strong><br />
如果用Innodb，那么这是一个重要变量。相对于MyISAM来说，Innodb对于buffer size更敏感。MySIAM可能对于大数据量使用默认的key_buffer_size也还好，但Innodb在大数据量时用默认值就感觉在爬了。 Innodb的缓冲池会缓存数据和索引，所以不需要给系统的缓存留空间，如果只用Innodb，可以把这个值设为内存的70%-80%。和 key_buffer相同，如果数据量比较小也不怎么增加，那么不要把这个值设太高也可以提高内存的使用率。<br />
<strong>innodb_additional_pool_size</strong><br />
这个的效果不是很明显，至少是当操作系统能合理分配内存时。但你可能仍需要设成20M或更多一点以看Innodb会分配多少内存做其他用途。<br />
<strong>innodb_log_file_size</strong><br />
对于写很多尤其是大数据量时非常重要。要注意，大的文件提供更高的性能，但数据库恢复时会用更多的时间。我一般用64M-512M，具体取决于服务器的空间。<br />
<strong>innodb_log_buffer_size</strong><br />
默认值对于多数中等写操作和事务短的运用都是可以的。如果经常做更新或者使用了很多blob数据，应该增大这个值。但太大了也是浪费内存，因为1秒钟总会 flush（这个词的中文怎么说呢？）一次，所以不需要设到超过1秒的需求。8M-16M一般应该够了。小的运用可以设更小一点。<br />
<strong>innodb_flush_log_at_trx_commit</strong> （这个很管用）<br />
抱怨Innodb比MyISAM慢 100倍？那么你大概是忘了调整这个值。默认值1的意思是每一次事务提交或事务外的指令都需要把日志写入（flush）硬盘，这是很费时的。特别是使用电 池供电缓存（Battery backed up cache）时。设成2对于很多运用，特别是从MyISAM表转过来的是可以的，它的意思是不写入硬盘而是写入系统缓存。日志仍然会每秒flush到硬 盘，所以你一般不会丢失超过1-2秒的更新。设成0会更快一点，但安全方面比较差，即使MySQL挂了也可能会丢失事务的数据。而值2只会在整个操作系统 挂了时才可能丢数据。</p>
<p>上面是网上看的，我发现慢查询日志内有很多update和insert的查询，就把innodb_flush_log_at_trx_commit改成了2，效果很明显，改成0会更明显，但安全性比较差。做下面的操作启动mysqld就生效：<br />
vim /etc/my.cnf<br />
innodb_flush_log_at_trx_commit=2</p>
<p>也可以在mysqld运行时执行：<br />
set GLOBAL innodb_flush_log_at_trx_commit = 2</p>
<p>下面是mysql手册上innodb_flush_log_at_trx_commit的解释：<br />
如果innodb_flush_log_at_trx_commit设置为0，log buffer将每秒一次地写入log file中，并且log file的flush(刷到磁盘)操作同时进行；但是，这种模式下，在事务提交的时候，不会有任何动作。如果 innodb_flush_log_at_trx_commit设置为1(默认值)，log buffer每次事务提交都会写入log file，并且，flush刷到磁盘中去。如果innodb_flush_log_at_trx_commit设置为2，log buffer在每次事务提交的时候都会写入log file，但是，flush(刷到磁盘)操作并不会同时进行。这种模式下，MySQL会每秒一次地去做flush(刷到磁盘)操作。注意：由于进程调度策 略问题，这个“每秒一次的flush(刷到磁盘)操作”并不是保证100%的“每秒”。<br />
默认值1是为了ACID (atomicity, consistency, isolation, durability)原子性，一致性，隔离性和持久化的考虑。如果你不把innodb_flush_log_at_trx_commit设置为1，你将获得更好的性能，但是，你在系统崩溃的情况，可能会丢失最多一秒钟的事务数据。当你把innodb_flush_log_at_trx_commit设置 为0，mysqld进程的崩溃会导致上一秒钟所有事务数据的丢失。如果你把innodb_flush_log_at_trx_commit设置为2，只有在操作系统崩溃或者系统掉电的情况下，上一秒钟所有事务数据才可能丢失。InnoDB的crash recovery崩溃恢复机制并不受这个值的影响，不管这个值设置为多少，crash recovery崩溃恢复机制都会工作。</p>
<p>另外<strong>innodb_flush_method</strong>参数也值得关注，对写操作有影响：<br />
innodb_flush_method： 设置InnoDB同步IO的方式：<br />
1) Default – 使用fsync（）。<br />
2) O_SYNC 以sync模式打开文件，通常比较慢。<br />
3) O_DIRECT，在Linux上使用Direct IO。可以显著提高速度，特别是在RAID系统上。避免额外的数据复制和double buffering（mysql buffering 和OS buffering）。</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2010%2F03%2F07%2Fmysql-view%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql%25E5%2586%2599%25E5%2585%25A5%25E4%25BC%2598%25E5%258C%2596%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL视图介绍</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2011%2F05%2F06%2Fmysql-5-1-56-innodb-plugin%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql%25E5%2586%2599%25E5%2585%25A5%25E4%25BC%2598%25E5%258C%2596%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL 5.1.56 使用 InnoDB Plugin</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2010%2F03%2F07%2Fmysql-root-lose%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql%25E5%2586%2599%25E5%2585%25A5%25E4%25BC%2598%25E5%258C%2596%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">mysql root帐号丢失解决办法</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2010%2F05%2F28%2Fphp-mysql-procedure%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql%25E5%2586%2599%25E5%2585%25A5%25E4%25BC%2598%25E5%258C%2596%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">PHP中操作mysql执行存储过程</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2011%2F11%2F16%2Fmysql-union-order-by-problem%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql%25E5%2586%2599%25E5%2585%25A5%25E4%25BC%2598%25E5%258C%2596%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Mysql中union和order by的问题及优先级</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/08/30/mysql%e5%86%99%e5%85%a5%e4%bc%98%e5%8c%96/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>mysql分页limit 优化</title>
		<link>http://fendou.org/2011/08/30/mysql-limit-opt/</link>
		<comments>http://fendou.org/2011/08/30/mysql-limit-opt/#comments</comments>
		<pubDate>Tue, 30 Aug 2011 14:56:38 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Excellence Article]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=844</guid>
		<description><![CDATA[mysql的分页比较简单，只需要limit offset,length就可以获取数据了，但是当offset和length比较大的时候，mysql明显性能下降 1.子查询优化法 先找出第一条数据，然后大于等于这条数据的id就是要获取的数据 缺点：数据必须是连续的，可以说不能有where条件，where条件会筛选数据，导致数据失去连续性 实验下 Sql代码  mysql&#62; set profiling=1; Query OK, 0 rows affected (0.00 sec) mysql&#62; select count(*) from Member; +&#8212;&#8212;&#8212;-+ &#124; count(*) &#124; +&#8212;&#8212;&#8212;-+ &#124;   169566 &#124; +&#8212;&#8212;&#8212;-+ 1 row in set (0.00 sec) mysql&#62; pager grep !~- PAGER set to &#8217;grep !~-&#8217; mysql&#62; select * from Member limit 10, 100; 100 rows in set (0.00 sec) mysql&#62; select * from Member where MemberID &#62;= (select MemberID from Member limit 10,1) limit 100; 100 rows in set (0.00 sec) mysql&#62; select * from Member limit 1000, 100; 100 rows in set (0.01 sec) mysql&#62; select * from Member where MemberID &#62;= (select MemberID from Member limit 1000,1) limit 100; 100 rows in set (0.00 sec) mysql&#62; select * from Member limit 100000, 100; 100 rows in set (0.10 sec) mysql&#62; select * from Member where MemberID &#62;= (select MemberID from Member limit 100000,1) limit 100; 100 rows in set (0.02 sec) mysql&#62; nopager PAGER set to stdout mysql&#62; show profiles\G *************************** 1. row *************************** Query_ID: 1 Duration: 0.00003300 Query: select count(*) from Member *************************** 2. row *************************** Query_ID: 2 Duration: 0.00167000 &#8230; <a href="http://fendou.org/2011/08/30/mysql-limit-opt/">继续阅读 <span class="meta-nav">&#8594;</span></a><table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2009%2F07%2F05%2Fmysql-index-limit%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql-limit-opt%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL中索引限制</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2010%2F05%2F28%2Fphp-mysql-procedure%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql-limit-opt%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">PHP中操作mysql执行存储过程</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2010%2F03%2F07%2Fmysql-view%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql-limit-opt%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL视图介绍</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2011%2F05%2F06%2Fmysql-5-1-56-innodb-plugin%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql-limit-opt%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL 5.1.56 使用 InnoDB Plugin</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Ffendou.org%2F2011%2F05%2F06%2Fmysql-communication-protocols%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F08%2F30%2Fmysql-limit-opt%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">MySQL通信协议</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>mysql的分页比较简单，只需要limit offset,length就可以获取数据了，但是当offset和length比较大的时候，mysql明显性能下降</p>
<p><strong>1.子查询优化法</strong><br />
先找出第一条数据，然后大于等于这条数据的id就是要获取的数据<br />
缺点：数据必须是连续的，可以说不能有where条件，where条件会筛选数据，导致数据失去连续性</p>
<p>实验下</p>
<div>
<div>
<div>Sql代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://willko.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=mysql%3E%20set%20profiling%3D1%3B%0AQuery%20OK%2C%200%20rows%20affected%20(0.00%20sec)%0A%0Amysql%3E%20select%20count(*)%20from%20Member%3B%0A%2B----------%2B%0A%7C%20count(*)%20%7C%0A%2B----------%2B%0A%7C%20%20%20169566%20%7C%20%0A%2B----------%2B%0A1%20row%20in%20set%20(0.00%20sec)%0A%0Amysql%3E%20pager%20grep%20!~-%0APAGER%20set%20to%20'grep%20!~-'%0A%0Amysql%3E%20select%20*%20from%20Member%20limit%2010%2C%20100%3B%0A100%20rows%20in%20set%20(0.00%20sec)%0A%0Amysql%3E%20select%20*%20from%20Member%20where%20MemberID%20%3E%3D%20(select%20MemberID%20from%20Member%20limit%2010%2C1)%20limit%20100%3B%0A100%20rows%20in%20set%20(0.00%20sec)%0A%0Amysql%3E%20select%20*%20from%20Member%20limit%201000%2C%20100%3B%0A100%20rows%20in%20set%20(0.01%20sec)%0A%0Amysql%3E%20select%20*%20from%20Member%20where%20MemberID%20%3E%3D%20(select%20MemberID%20from%20Member%20limit%201000%2C1)%20limit%20100%3B%0A100%20rows%20in%20set%20(0.00%20sec)%0A%0Amysql%3E%20select%20*%20from%20Member%20limit%20100000%2C%20100%3B%0A100%20rows%20in%20set%20(0.10%20sec)%0A%0Amysql%3E%20select%20*%20from%20Member%20where%20MemberID%20%3E%3D%20(select%20MemberID%20from%20Member%20limit%20100000%2C1)%20limit%20100%3B%0A100%20rows%20in%20set%20(0.02%20sec)%0A%0Amysql%3E%20nopager%0APAGER%20set%20to%20stdout%0A%0A%0Amysql%3E%20show%20profiles%5CG%0A***************************%201.%20row%20***************************%0AQuery_ID%3A%201%0ADuration%3A%200.00003300%0A%20%20%20Query%3A%20select%20count(*)%20from%20Member%0A%0A***************************%202.%20row%20***************************%0AQuery_ID%3A%202%0ADuration%3A%200.00167000%0A%20%20%20Query%3A%20select%20*%20from%20Member%20limit%2010%2C%20100%0A***************************%203.%20row%20***************************%0AQuery_ID%3A%203%0ADuration%3A%200.00112400%0A%20%20%20Query%3A%20select%20*%20from%20Member%20where%20MemberID%20%3E%3D%20(select%20MemberID%20from%20Member%20limit%2010%2C1)%20limit%20100%0A%0A***************************%204.%20row%20***************************%0AQuery_ID%3A%204%0ADuration%3A%200.00263200%0A%20%20%20Query%3A%20select%20*%20from%20Member%20limit%201000%2C%20100%0A***************************%205.%20row%20***************************%0AQuery_ID%3A%205%0ADuration%3A%200.00134000%0A%20%20%20Query%3A%20select%20*%20from%20Member%20where%20MemberID%20%3E%3D%20(select%20MemberID%20from%20Member%20limit%201000%2C1)%20limit%20100%0A%0A***************************%206.%20row%20***************************%0AQuery_ID%3A%206%0ADuration%3A%200.09956700%0A%20%20%20Query%3A%20select%20*%20from%20Member%20limit%20100000%2C%20100%0A***************************%207.%20row%20***************************%0AQuery_ID%3A%207%0ADuration%3A%200.02447700%0A%20%20%20Query%3A%20select%20*%20from%20Member%20where%20MemberID%20%3E%3D%20(select%20MemberID%20from%20Member%20limit%20100000%2C1)%20limit%20100" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed> <a title="收藏这段代码" href="http://willko.iteye.com/blog/325618"><img src="http://willko.iteye.com/images/icon_star.png" alt="收藏代码" /></a></div>
</div>
<ol>
<li>mysql&gt; set profiling=1;</li>
<li>Query OK, 0 rows affected (0.00 sec)</li>
<li></li>
<li>mysql&gt; select count(*) from Member;</li>
<li>+&#8212;&#8212;&#8212;-+</li>
<li>| count(*) |</li>
<li>+&#8212;&#8212;&#8212;-+</li>
<li>|   169566 |</li>
<li>+&#8212;&#8212;&#8212;-+</li>
<li>1 row in set (0.00 sec)</li>
<li></li>
<li>mysql&gt; pager grep !~-</li>
<li>PAGER set to &#8217;grep !~-&#8217;</li>
<li></li>
<li>mysql&gt; select * from Member limit 10, 100;</li>
<li>100 rows in set (0.00 sec)</li>
<li></li>
<li>mysql&gt; select * from Member where MemberID &gt;= (select MemberID from Member limit 10,1) limit 100;</li>
<li>100 rows in set (0.00 sec)</li>
<li></li>
<li>mysql&gt; select * from Member limit 1000, 100;</li>
<li>100 rows in set (0.01 sec)</li>
<li></li>
<li>mysql&gt; select * from Member where MemberID &gt;= (select MemberID from Member limit 1000,1) limit 100;</li>
<li>100 rows in set (0.00 sec)</li>
<li></li>
<li>mysql&gt; select * from Member limit 100000, 100;</li>
<li>100 rows in set (0.10 sec)</li>
<li></li>
<li>mysql&gt; select * from Member where MemberID &gt;= (select MemberID from Member limit 100000,1) limit 100;</li>
<li>100 rows in set (0.02 sec)</li>
<li></li>
<li>mysql&gt; nopager</li>
<li>PAGER set to stdout</li>
<li></li>
<li></li>
<li>mysql&gt; show profiles\G</li>
<li>*************************** 1. row ***************************</li>
<li>Query_ID: 1</li>
<li>Duration: 0.00003300</li>
<li> Query: select count(*) from Member</li>
<li></li>
<li>*************************** 2. row ***************************</li>
<li>Query_ID: 2</li>
<li>Duration: 0.00167000</li>
<li> Query: select * from Member limit 10, 100</li>
<li>*************************** 3. row ***************************</li>
<li>Query_ID: 3</li>
<li>Duration: 0.00112400</li>
<li> Query: select * from Member where MemberID &gt;= (select MemberID from Member limit 10,1) limit 100</li>
<li></li>
<li>*************************** 4. row ***************************</li>
<li>Query_ID: 4</li>
<li>Duration: 0.00263200</li>
<li> Query: select * from Member limit 1000, 100</li>
<li>*************************** 5. row ***************************</li>
<li>Query_ID: 5</li>
<li>Duration: 0.00134000</li>
<li> Query: select * from Member where MemberID &gt;= (select MemberID from Member limit 1000,1) limit 100</li>
<li></li>
<li>*************************** 6. row ***************************</li>
<li>Query_ID: 6</li>
<li>Duration: 0.09956700</li>
<li> Query: select * from Member limit 100000, 100</li>
<li>*************************** 7. row ***************************</li>
<li>Query_ID: 7</li>
<li>Duration: 0.02447700</li>
<li> Query: select * from Member where MemberID &gt;= (select MemberID from Member limit 100000,1) limit 100</li>
</ol>
</div>
<p>从结果中可以得知，当偏移1000以上使用子查询法可以有效的提高性能。</p>
<p><strong>2.倒排表优化法</strong><br />
倒排表法类似建立索引，用一张表来维护页数，然后通过高效的连接得到数据</p>
<p>缺点：只适合数据数固定的情况，数据不能删除，维护页表困难</p>
<p>具体请看，<a href="http://blog.chinaunix.net/u/29134/showart_1333566.html" target="_blank">http://blog.chinaunix.net/u/29134/showart_1333566.html</a></p>
<p><strong>3.反向查找优化法</strong><br />
当偏移超过一半记录数的时候，先用排序，这样偏移就反转了</p>
<p>缺点：order by优化比较麻烦，要增加索引，索引影响数据的修改效率，并且要知道总记录数<br />
，偏移大于数据的一半</p>
<div>引用</div>
<div>limit偏移算法：<br />
正向查找： (当前页 &#8211; 1) * 页长度<br />
反向查找： 总记录 &#8211; 当前页 * 页长度</div>
<p>做下实验，看看性能如何</p>
<p>总记录数：1,628,775<br />
每页记录数： 40<br />
总页数：1,628,775 / 40 = 40720<br />
中间页数：40720 / 2 = 20360</p>
<p>第21000页<br />
正向查找SQL:</p>
<div>
<div>
<div>Sql代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://willko.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=SELECT%20*%20FROM%20%60abc%60%20WHERE%20%60BatchID%60%20%3D%20123%20LIMIT%20839960%2C%2040" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed> <a title="收藏这段代码" href="http://willko.iteye.com/blog/325618"><img src="http://willko.iteye.com/images/icon_star.png" alt="收藏代码" /></a></div>
</div>
<ol>
<li>SELECT * FROM `abc` WHERE `BatchID` = 123 LIMIT 839960, 40</li>
</ol>
</div>
<p>时间：1.8696 秒</p>
<p>反向查找sql:</p>
<div>
<div>
<div>Sql代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://willko.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=SELECT%20*%20FROM%20%60abc%60%20WHERE%20%60BatchID%60%20%3D%20123%20ORDER%20BY%20InputDate%20DESC%20LIMIT%20788775%2C%2040" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed> <a title="收藏这段代码" href="http://willko.iteye.com/blog/325618"><img src="http://willko.iteye.com/images/icon_star.png" alt="收藏代码" /></a></div>
</div>
<ol>
<li>SELECT * FROM `abc` WHERE `BatchID` = 123 ORDER BY InputDate DESC LIMIT 788775, 40</li>
</ol>
</div>
<p>时间：1.8336 秒</p>
<p>第30000页<br />
正向查找SQL:</p>
<div>
<div>
<div>Sql代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://willko.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=SELECT%20*%20FROM%20%60abc%60%20WHERE%20%60BatchID%60%20%3D%20123%20LIMIT%201199960%2C%2040" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed> <a title="收藏这段代码" href="http://willko.iteye.com/blog/325618"><img src="http://willko.iteye.com/images/icon_star.png" alt="收藏代码" /></a></div>
</div>
<ol>
<li>SELECT * FROM `abc` WHERE `BatchID` = 123 LIMIT 1199960, 40</li>
</ol>
</div>
<p>时间：2.6493 秒</p>
<p>反向查找sql:</p>
<div>
<div>
<div>Sql代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://willko.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=SELECT%20*%20FROM%20%60abc%60%20WHERE%20%60BatchID%60%20%3D%20123%20ORDER%20BY%20InputDate%20DESC%20LIMIT%20428775%2C%2040" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed> <a title="收藏这段代码" href="http://willko.iteye.com/blog/325618"><img src="http://willko.iteye.com/images/icon_star.png" alt="收藏代码" /></a></div>
</div>
<ol>
<li>SELECT * FROM `abc` WHERE `BatchID` = 123 ORDER BY InputDate DESC LIMIT 428775, 40</li>
</ol>
</div>
<p>时间：1.0035 秒</p>
<p>注意，反向查找的结果是是降序desc的，并且InputDate是记录的插入时间，也可以用主键联合索引，但是不方便。</p>
<p><strong>4.limit限制优化法</strong><br />
把limit偏移量限制低于某个数。。超过这个数等于没数据，我记得alibaba的dba说过他们是这样做的</p>
<p><strong>5.只查索引法</strong><br />
<a href="http://willko.iteye.com/blog/670120" target="_blank">http://willko.iteye.com/blog/670120</a></p>
<p>总结：limit的优化限制都比较多，所以实际情况用或者不用只能具体情况具体分析了。页数那么后，基本很少人看的。。。</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/08/30/mysql-limit-opt/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hive使用笔记</title>
		<link>http://fendou.org/2011/06/08/hive%e4%bd%bf%e7%94%a8%e7%ac%94%e8%ae%b0/</link>
		<comments>http://fendou.org/2011/06/08/hive%e4%bd%bf%e7%94%a8%e7%ac%94%e8%ae%b0/#comments</comments>
		<pubDate>Wed, 08 Jun 2011 01:45:04 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Excellence Article]]></category>
		<category><![CDATA[Study & Reading]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=832</guid>
		<description><![CDATA[Hive是为提供简单的数据操作而设计的下一代分布式数据仓库。它提供了简单的类似SQL的语法的HiveQL语言进行数据查询。同时，HiveQL语言能力不足时，它也能允许使用传统的map/reduce进行复杂数据分析。 Hive是搭建在Hadoop平台之上的。Hive并不是一个真正的数据库，它的元数据需要存储在其他数据库中(例如mysql)。。Hadoop平台提供了HDFS分布式存储系统和map/reduce分布式计算系统，而Hive在这两个系统之上，使得用户只需使用熟悉SQL语言就能进行分布式计算，而map/reduce编程往往是相当复杂的。Hive在少量数据运算或是短时间内的重复查询上，是不能和Oracle那样的数据库相比的。它的查询量通常相当大，一个大的job运行几个小时算是正常的。 数据类型 。HiveQL只支持以下几种基本数据类型TINYINT, SMALLINT, INT, BIGINT, DOUBLE, STRING。 支持的复杂数据类型有Structs, Maps, Arrays。 创建表。 Hive不同于其他数据库，它只有一个默认数据库”default” ，所有的table都保持在里面。 CREATE TABLE user(id BIGINT, name STRING); 可以指定将表创建到外部hdfs文件系统中。 CREATE EXTERNAL TABLE foo(id INT) STORED AS TEXTFILE LOCALTION &#8216;/user/foo/foo_data&#8217;; 将数据文件导入到Hive表中。 LOAD DATA [LOCAL] INPATH &#8216;/data/userdata&#8217; [OVERWRITE] INTO &#8230; <a href="http://fendou.org/2011/06/08/hive%e4%bd%bf%e7%94%a8%e7%ac%94%e8%ae%b0/">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Hive是为提供简单的数据操作而设计的下一代分布式数据仓库。它提供了简单的类似SQL的语法的HiveQL语言进行数据查询。同时，HiveQL语言能力不足时，它也能允许使用传统的map/reduce进行复杂数据分析。</p>
<p>Hive是搭建在Hadoop平台之上的。Hive并不是一个真正的数据库，它的元数据需要存储在其他数据库中(例如mysql)。。Hadoop平台提供了HDFS分布式存储系统和map/reduce分布式计算系统，而Hive在这两个系统之上，使得用户只需使用熟悉SQL语言就能进行分布式计算，而map/reduce编程往往是相当复杂的。Hive在少量数据运算或是短时间内的重复查询上，是不能和Oracle那样的数据库相比的。它的查询量通常相当大，一个大的job运行几个小时算是正常的。</p>
<p>数据类型 。HiveQL只支持以下几种基本数据类型TINYINT, SMALLINT, INT, BIGINT, DOUBLE, STRING。</p>
<p>支持的复杂数据类型有Structs, Maps, Arrays。</p>
<p>创建表。 Hive不同于其他数据库，它只有一个默认数据库”default” ，所有的table都保持在里面。</p>
<p>CREATE TABLE user(id BIGINT, name STRING);</p>
<p>可以指定将表创建到外部hdfs文件系统中。</p>
<p>CREATE EXTERNAL TABLE foo(id INT)</p>
<p>STORED AS TEXTFILE LOCALTION &#8216;/user/foo/foo_data&#8217;;</p>
<p>将数据文件导入到Hive表中。</p>
<p>LOAD DATA [LOCAL] INPATH &#8216;/data/userdata&#8217; [OVERWRITE] INTO TABLE user;</p>
<p>使用LOCAL选项将使用本地文件系统 ，否则将使用hdfs文件系统。使用OVERWRITE选项将删除原来table中的数据，否则将新数据添加到文件末尾。</p>
<p>Load data导入数据将仅仅将文件拷贝到hive管理的目录下，并用table的元数据去解释这个文件。所以必须保证数据文件的结构必须和table的结构一 致，否则可以load data成功但是数据解释不正确。特别注意fields分隔符和lines分隔符要和Table一致。我使用自定义分隔符导入数据，一直没有成功。不管我 怎么指定，Hive总是使用默认的分隔符来解释我的文件（默认使用001(ctrl-A)分隔列，012(\n)分隔行 ）。问题未解决。</p>
<p>查询语句。 这里列出一些和标准SQL不同的地方。</p>
<p>不能使用select count(*)；需要指定count的列下标，select count(1) 。</p>
<p>不能使用CREATE TABLE newtable SELECT * FROM user；必须事先Create table，再用INSERT向其中写入数据。</p>
<p>排序关键字是SORT BY。</p>
<p>LIMIT关键字只能跟一个数字，即从第一条记录开始选出若干条。</p>
<p>INSERT语句变换很大，不能直接插入一条记录。插入的数据必须用SELECT子查询获取或者从某个文件导入。我还没细看。</p>
<p>> SELECT * FROM user LIMIT 10;</p>
<p>> INSERT OVERWRITE TABLE foo SELECT DESTIN(id) FROM user;</p>
<p>> SELECT M.id FROM user M JOIN foo S ON M.id = S.id;</p>
<p>> SELECT id FROM user GROUP BY id;</p>
]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/06/08/hive%e4%bd%bf%e7%94%a8%e7%ac%94%e8%ae%b0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySQL通信协议</title>
		<link>http://fendou.org/2011/05/06/mysql-communication-protocols/</link>
		<comments>http://fendou.org/2011/05/06/mysql-communication-protocols/#comments</comments>
		<pubDate>Fri, 06 May 2011 15:26:40 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=825</guid>
		<description><![CDATA[MySQL实现了四种通信协议 TCP/IP协议，通常我们通过来连接MySQL，各种主要编程语言都是根据这个协议实现了连接模块 Unix Socket协议，这个通常我们登入MySQL服务器中使用这个协议，因为要使用这个协议连接MySQL需要一个物理文件，文件的存放位置在配置文件中有定义，值得一提的是，这是所有协议中最高效的一个。 Share Memory协议，这个协议一般人不知道，肯定也没用过，因为这个只有windows可以使用，使用这个协议需要在配置文件中在启动的时候使用&#8211;shared-memory参数，注意的是，使用此协议，一个host上只能有一个server，所以这个东西一般没啥用的，除非你怀疑其他协议不能正常工作，实际上微软的SQL Sever也支持这个协议 Named Pipes协议，这个协议也是只有windows才可以用，同shared memory一样，使用此协议，一个host上依然只能有一个server，即使是使用不同的端口也不行，Named Pipes 是为局域网而开发的协议。内存的一部分被某个进程用来向另一个进程传递信息，因此一个进程的输出就是另一个进程的输入。第二个进程可以是本地的（与第一个进程位于同一台计算机上），也可以是远程的（位于联网的计算机上）。正因为如此，假如你的环境中没有或者禁用TCP/IP环境，而且是windows服务器，那么好歹你的数据库还能工作。使用这个协议需要在启动的时候添加&#8211;enable-named-pipe选项 Named Pipes和Shared Memory协议都非常的低效，而且只能用于windows环境，非必要情况尽量避免使用]]></description>
			<content:encoded><![CDATA[<p>MySQL实现了四种通信协议</p>
<ol>
<li>TCP/IP协议，通常我们通过来连接MySQL，各种主要编程语言都是根据这个协议实现了连接模块</li>
<li>Unix Socket协议，这个通常我们登入MySQL服务器中使用这个协议，因为要使用这个协议连接MySQL需要一个物理文件，文件的存放位置在配置文件中有定义，值得一提的是，这是所有协议中最高效的一个。</li>
<li>Share Memory协议，这个协议一般人不知道，肯定也没用过，因为这个只有windows可以使用，使用这个协议需要在配置文件中在启动的时候使用&#8211;shared-memory参数，注意的是，使用此协议，一个host上只能有一个server，所以这个东西一般没啥用的，除非你怀疑其他协议不能正常工作，实际上微软的SQL Sever也支持这个协议</li>
<li>Named Pipes协议，这个协议也是只有windows才可以用，同shared memory一样，使用此协议，一个host上依然只能有一个server，即使是使用不同的端口也不行，Named Pipes 是为局域网而开发的协议。内存的一部分被某个进程用来向另一个进程传递信息，因此一个进程的输出就是另一个进程的输入。第二个进程可以是本地的（与第一个进程位于同一台计算机上），也可以是远程的（位于联网的计算机上）。正因为如此，假如你的环境中没有或者禁用TCP/IP环境，而且是windows服务器，那么好歹你的数据库还能工作。使用这个协议需要在启动的时候添加&#8211;enable-named-pipe选项</li>
</ol>
<p><span style="font-size: small;"><span style="line-height: 24px;"><span style="color: #ff0000;">Named Pipes和Shared Memory协议都非常的低效，而且只能用于windows环境，非必要情况尽量避免使用</span><br />
</span></span></p>
<p><span style="font-size: small;"><span style="line-height: 24px;"><br />
</span></span></p>
]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/05/06/mysql-communication-protocols/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>MySQL 5.1.56 使用 InnoDB Plugin</title>
		<link>http://fendou.org/2011/05/06/mysql-5-1-56-innodb-plugin/</link>
		<comments>http://fendou.org/2011/05/06/mysql-5-1-56-innodb-plugin/#comments</comments>
		<pubDate>Fri, 06 May 2011 12:58:30 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=821</guid>
		<description><![CDATA[[root@localhost mysql-5.1.56]# ./configure --prefix=/usr/local/mysql/ \ --without-debug \ --with-unix-socket-path=/usr/local/mysql/tmp/mysql.sock \ --with-client-ldflags=-all-static \ --with-mysqld-ldflags=-all-static \ --enable-assembler \ --with-charset=utf8 \ --with-collation=utf8_general_ci \ --with-extra-charsets=latin1,gb2312 \ --with-pthread --enable-thread-safe-client \ --with-plugins=myisam,innodb_plugin]]></description>
			<content:encoded><![CDATA[
<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">[root@localhost mysql-5.1.56]# ./configure --prefix=/usr/local/mysql/ \
--without-debug \
--with-unix-socket-path=/usr/local/mysql/tmp/mysql.sock \
--with-client-ldflags=-all-static \
--with-mysqld-ldflags=-all-static \
--enable-assembler  \
--with-charset=utf8 \
--with-collation=utf8_general_ci \
--with-extra-charsets=latin1,gb2312 \
--with-pthread --enable-thread-safe-client   \
--with-plugins=myisam,innodb_plugin</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/05/06/mysql-5-1-56-innodb-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySQL 先排序再分组的问题</title>
		<link>http://fendou.org/2010/09/29/mysql-order-and-group_by/</link>
		<comments>http://fendou.org/2010/09/29/mysql-order-and-group_by/#comments</comments>
		<pubDate>Wed, 29 Sep 2010 04:14:02 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Excellence Article]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=731</guid>
		<description><![CDATA[group是分组,想先排序如何办? 建一个表试试 &#8211; &#8211; 表的结构 `test` &#8211; CREATE TABLE IF NOT EXISTS `test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(16) NOT NULL, `phone` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; &#8211; &#8211; 导出表中的数据 `test` &#8211; INSERT &#8230; <a href="http://fendou.org/2010/09/29/mysql-order-and-group_by/">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>group是分组,想先排序如何办?</p>
<p>建一个表试试</p>
<p>&#8211;<br />
&#8211; 表的结构 `test`<br />
&#8211;</p>
<p>CREATE TABLE IF NOT EXISTS `test` (<br />
  `id` int(11) NOT NULL AUTO_INCREMENT,<br />
  `name` varchar(16) NOT NULL,<br />
  `phone` int(11) NOT NULL,<br />
  PRIMARY KEY (`id`)<br />
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;</p>
<p>&#8211;<br />
&#8211; 导出表中的数据 `test`<br />
&#8211;</p>
<p>INSERT INTO `test` (`id`, `name`, `phone`) VALUES<br />
(1, &#8216;a&#8217;, 1234),<br />
(2, &#8216;a&#8217;, 3333),<br />
(3, &#8216;b&#8217;, 555),<br />
(4, &#8216;b&#8217;, 6773),<br />
(5, &#8216;a&#8217;, 743),<br />
(6, &#8216;c&#8217;, 95434);</p>
<p>查询一下,<br />
SELECT * FROM `test` group by name<br />
得到<br />
id     name     phone<br />
1     a     1234<br />
3     b     555<br />
6     c     95434</p>
<p>但我们想得到id最大的name怎么办?<br />
SELECT max(id),id,name,phone FROM test group by name<br />
得到<br />
max(id) id     name     phone<br />
5     1     a     1234<br />
4     3     b     555<br />
6     6     c     95434<br />
可以看到,虽然每个name的最大id得到了,但是,其他数据依然是每个name的第一行<br />
用子查询<br />
select * from (select * from test order by id desc) t group by name<br />
得到<br />
id     name     phone<br />
5     a     743<br />
4     b     6773<br />
6     c     95434<br />
这就是我们想要的结果了,但是,这种作法在行数非常多的情况下,相当于把整个表复制了一次,估计效率低.<br />
那用这种子查询<br />
select * from test t where id in  (select max(id) from test group by name)<br />
得到<br />
id     name     phone<br />
4     b     6773<br />
5     a     743<br />
6     c     95434<br />
然而,这种子查询因为用了in,在数量多的情况下,也许还更慢些?不确定,没时间测试<br />
另外,还有一种方法,不过原理我也有些糊涂了,只是看网上有人这样作,<br />
select * from test t inner join (select * from test order by id desc) t2 on t.id=t2.id group by t.name<br />
得到<br />
id     name     phone     id     name     phone<br />
5     a     743     5     a     743<br />
4     b     6773     4     b     6773<br />
6     c     95434     6     c     95434<br />
为了想提高效率,想到了视图,先按id desc排个视图,再group by name,岂不是相当于子查询?<br />
CREATE VIEW `testv` AS select `test`.`id` AS `id`,`test`.`name` AS `name`,`test`.`phone` AS `phone` from `test` order by `test`.`id` desc;<br />
视图建立了,再查询<br />
SELECT * FROM `testv` group by name<br />
结果竟然是<br />
id     name     phone<br />
1     a     1234<br />
3     b     555<br />
6     c     95434<br />
和在原表用<br />
SELECT * FROM `test` group by name<br />
的结果一样.看来视图和真正的表毕竟是有区别的</p>
<p>补充:<br />
上网再看了一下,原来第二种子查询方法网上不是那样的,尽管我那样写在这个例子上也成功了,但是,说不定其他表会错?没时间测试.网上的方法是<br />
select * from test t inner join (select max(id) as id,name from test group by name) t2 on t.id=t2.id and t.name=t2.name<br />
得到<br />
id     name     phone     id     name<br />
5     a        743          5     a<br />
4     b       6773          4     b<br />
6     c       95434         6     c<br />
另外,把上面这些查询方法中的test表换成testv,都可以得到正确的结果,尽管order by有点不同.<br />
上面的排序都只针对一个字段,两个及以上字段也可以采用类似于<br />
select * from (select * from test order by id desc) t group by name<br />
这样的方法,在子查询中可以多个字段来order by<br />
下面删除原来的test,重建一下<br />
&#8211;<br />
&#8211; 表的结构 `test`<br />
&#8211;</p>
<p>CREATE TABLE IF NOT EXISTS `test` (<br />
  `id` int(11) NOT NULL AUTO_INCREMENT,<br />
  `name` varchar(16) NOT NULL,<br />
  `month` int(11) NOT NULL,<br />
  `serial` int(11) NOT NULL,<br />
  `other` varchar(20) NOT NULL,<br />
  PRIMARY KEY (`id`)<br />
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;</p>
<p>&#8211;<br />
&#8211; 导出表中的数据 `test`<br />
&#8211;</p>
<p>INSERT INTO `test` (`id`, `name`, `month`, `serial`, `other`) VALUES<br />
(1, &#8216;a&#8217;, 200807, 2, &#8216;aaa1&#8242;),<br />
(2, &#8216;a&#8217;, 200805, 2, &#8216;aaa2&#8242;),<br />
(3, &#8216;b&#8217;, 200805, 3, &#8216;bbb3&#8242;),<br />
(4, &#8216;b&#8217;, 200805, 4, &#8216;bbb4&#8242;),<br />
(5, &#8216;a&#8217;, 200805, 1, &#8216;aaa5&#8242;),<br />
(6, &#8216;c&#8217;, 200807, 5, &#8216;ccc6&#8242;),<br />
(7, &#8216;b&#8217;, 200807, 8, &#8216;bbb7&#8242;),<br />
(8, &#8216;c&#8217;, 200807, 3, &#8216;ccc8&#8242;),<br />
(9, &#8216;a&#8217;, 200805, 6, &#8216;aaa9&#8242;);</p>
<p>查询<br />
select * from (select * from test order by month desc,serial desc) t group by name<br />
得到<br />
id     name     month     serial     other<br />
1     a     200807     2     aaa1<br />
7     b     200807     8     bbb7<br />
6     c     200807     5     ccc6<br />
换一下排序方式<br />
select * from (select * from test order by month asc,serial desc) t group by name<br />
得到<br />
id     name     month     serial     other<br />
9     a     200805     6     aaa9<br />
4     b     200805     4     bbb4<br />
6     c     200807     5     ccc6<br />
都按我们的要求显示了结果</p>
]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2010/09/29/mysql-order-and-group_by/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP中操作mysql执行存储过程</title>
		<link>http://fendou.org/2010/05/28/php-mysql-procedure/</link>
		<comments>http://fendou.org/2010/05/28/php-mysql-procedure/#comments</comments>
		<pubDate>Fri, 28 May 2010 15:01:14 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=696</guid>
		<description><![CDATA[存储过程和函数是MySql5.0中引入的。关于这方面的操作在PHP里面没有直接的支持。但是由于Mysql PHP API的设计，使得我们可以在以前的PHP版本中的mysql php api中支持存储过程和函数的调用。 在php中调用存储过程和函数。 1.调用存储过程的方法。 a. 如果存储过程有 IN/INOUT参数，声明一个变量，输入参数给存储过程，该变量是一对， 一个php变量（也可以不必，只是没有php变量时，没有办法进行动态输入），一个Mysql变量。 b.如果存储过程有OUT变量，声明一个Mysql变量。mysql变量的声明比较特殊，必须让mysql服务器知道此变量的存在，其实也就是执行一条mysql语句。 如 set @mysqlvar=$phpvar ; c.使用mysql_query()/mysql_db_query()执行mysql 变量声明语句。 mysql_query(“set @mysqlvar [=$pbpvar]“); 这样，在mysql服务器里面就有一个变量，@mysqlar。如果时IN参数，那么其值可以有phpar传入。 d. 如果是存储过程。 1. 执行 call procedure（）语句。 也就是mysql_query(“call proceduer([var1]&#8230;)”); 2. 如果有返回值，执行select @ar，返回执行结果。 mysql_query(“select @var)” 接下来的操作就和php执行一般的mysql语句一样了。可以通过mydql_fetch_row()等函数获得结果。 如果时函数。 直接执行 select function（） &#8230; <a href="http://fendou.org/2010/05/28/php-mysql-procedure/">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>存储过程和函数是MySql5.0中引入的。关于这方面的操作在PHP里面没有直接的支持。但是由于Mysql PHP API的设计，使得我们可以在以前的PHP版本中的mysql php api中支持存储过程和函数的调用。</p>
<p>在php中调用存储过程和函数。</p>
<p>1.调用存储过程的方法。</p>
<p>a. 如果存储过程有 IN/INOUT参数，声明一个变量，输入参数给存储过程，该变量是一对， 一个php变量（也可以不必，只是没有php变量时，没有办法进行动态输入），一个Mysql变量。<br />
b.如果存储过程有OUT变量，声明一个Mysql变量。mysql变量的声明比较特殊，必须让mysql服务器知道此变量的存在，其实也就是执行一条mysql语句。<br />
     如  set @mysqlvar=$phpvar ;<br />
 c.使用mysql_query()/mysql_db_query()执行mysql 变量声明语句。<br />
mysql_query(“set @mysqlvar [=$pbpvar]“);<br />
这样，在mysql服务器里面就有一个变量，@mysqlar。如果时IN参数，那么其值可以有phpar传入。</p>
<p>d. 如果是存储过程。<br />
1. 执行 call procedure（）语句。<br />
      也就是mysql_query(“call proceduer([var1]&#8230;)”);<br />
2. 如果有返回值，执行select  @ar，返回执行结果。<br />
 mysql_query(“select @var)”<br />
 接下来的操作就和php执行一般的mysql语句一样了。可以通过mydql_fetch_row()等函数获得结果。<br />
如果时函数。 直接执行 select function（） 就可以了。</p>
<pre lang=''php">
$host="localhost";
    $user="root";
    $passWord="11212";
    $db="samp_db";
    $dblink=mysql_connect($host,$user,$password)
            or die("can't connect to mysql");
mysql_select_db($db,$dblink)
      or die("can't select samp_db");
    $res=mysql_query("set @a=$password",$dblink);
    $res=mysql_query("call aa(@a)",$dblink);
    $res=mysql_query("select @a",$dblink);
    $row=mysql_fetch_row($res);
    echo $row[0];
</pre>
]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2010/05/28/php-mysql-procedure/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Mysql存储过程学习笔记&#8211;变量、参数、注释</title>
		<link>http://fendou.org/2010/05/28/mysql-variable-params-comment/</link>
		<comments>http://fendou.org/2010/05/28/mysql-variable-params-comment/#comments</comments>
		<pubDate>Fri, 28 May 2010 14:50:37 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=694</guid>
		<description><![CDATA[变量定义: DECLARE variable_name [,variable_name...] datatype [DEFAULT value]; 其中，datatype为mysql的数据类型，如:INT, FLOAT, DATE, VARCHAR(length) 例: DECLARE l_int INT unsigned default 4000000; DECLARE l_numeric NUMERIC(8,2) DEFAULT 9.95; DECLARE l_date DATE DEFAULT &#8217;1999-12-31&#8242;; DECLARE l_datetime DATETIME DEFAULT &#8217;1999-12-31 23:59:59&#8242;; DECLARE l_varchar VARCHAR(255) DEFAULT &#8216;This will &#8230; <a href="http://fendou.org/2010/05/28/mysql-variable-params-comment/">继续阅读 <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="font: normal normal normal 12px/normal song, Verdana;"><strong><span style="text-decoration: underline;">变量定义:</span></strong></p>
<table style="font-size: 12px; width: 494px; border: 1px solid #999999;" border="0" align="center">
<tbody>
<tr style="font: normal normal normal 12px/normal song, Verdana;">
<td style="font: normal normal normal 12px/normal song, Verdana;">DECLARE variable_name [,variable_name...] datatype [DEFAULT value];</td>
</tr>
</tbody>
</table>
<p style="font: normal normal normal 12px/normal song, Verdana;">其中，datatype为mysql的数据类型，如:INT, FLOAT, DATE, VARCHAR(length)</p>
<p style="font: normal normal normal 12px/normal song, Verdana;">例:</p>
<p style="font: normal normal normal 12px/normal song, Verdana;">DECLARE l_int INT unsigned default 4000000; DECLARE l_numeric NUMERIC(8,2) DEFAULT 9.95; DECLARE l_date DATE DEFAULT &#8217;1999-12-31&#8242;; DECLARE l_datetime DATETIME DEFAULT &#8217;1999-12-31 23:59:59&#8242;; DECLARE l_varchar VARCHAR(255) DEFAULT &#8216;This will not be padded&#8217;;  <br style="font: normal normal normal 12px/normal song, Verdana;" /></p>
<p style="font: normal normal normal 12px/normal song, Verdana;"><strong><span style="text-decoration: underline;">变量赋值</span></strong></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">SET 变量名 = 表达式值 [,variable_name = expression ...]<br style="font: normal normal normal 12px/normal song, Verdana;" /></p>
<p style="font: normal normal normal 12px/normal song, Verdana;"><span style="text-decoration: underline;"><strong>参数</strong></span></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">mysql存储过程的参数用在存储过程的定义，共有三种参数类型,IN,OUT,INOUT</p>
<table style="font-size: 12px; width: 494px; border: 1px solid #999999;" border="0" align="center">
<tbody>
<tr style="font: normal normal normal 12px/normal song, Verdana;">
<td style="font: normal normal normal 12px/normal song, Verdana;">Create procedure|function([[IN |OUT |INOUT ] 参数名 数据类形&#8230;])</td>
</tr>
</tbody>
</table>
<p style="font: normal normal normal 12px/normal song, Verdana;"><strong>IN 输入参数</strong></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">表示该参数的值必须在调用存储过程时指定，在存储过程中修改该参数的值不能被返回，为默认值</p>
<p style="font: normal normal normal 12px/normal song, Verdana;"><strong>OUT 输出参数</strong></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">该值可在存储过程内部被改变，并可返回</p>
<p style="font: normal normal normal 12px/normal song, Verdana;"><strong>INOUT 输入输出参数</strong></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">调用时指定，并且可被改变和返回</p>
<p style="font: normal normal normal 12px/normal song, Verdana;"><strong>IN参数例子:</strong></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">创建</p>
<p style="font: normal normal normal 12px/normal song, Verdana;">mysql&gt; CREATE PROCEDURE sp_demo_in_parameter(IN p_in INT) BEGIN SELECT p_in; /*查询输入参数*/*/ SET p_in=2; /*修改*/ select p_in;/*查看修改后的值*/ END; <br style="font: normal normal normal 12px/normal song, Verdana;" />执行结果:<br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; set @p_in=1<br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; call sp_demo_in_parameter(@p_in)<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" />| p_in |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" />|    1 | <br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" />| p_in |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" />|    2 | <br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; select @p_in;<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />| @p_in |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />| 1     |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" /></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">以上可以看出，p_in虽然在存储过程中被修改，但并不影响@p_id的值</p>
<p style="font: normal normal normal 12px/normal song, Verdana;"><strong>OUT参数例子</strong></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">创建:</p>
<p style="font: normal normal normal 12px/normal song, Verdana;">mysql&gt; CREATE PROCEDURE sp_demo_out_parameter(OUT p_out INT) BEGIN SELECT p_out;/*查看输出参数*/ SET p_out=2;/*修改参数值*/ SELECT p_out;/*看看有否变化*/ END; <br style="font: normal normal normal 12px/normal song, Verdana;" />执行结果:<br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; SET @p_out=1<br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; CALL sp_demo_out_parameter(@p_out)<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />| p_out | <br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />|  NULL | <br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />/*未被定义，返回NULL*/<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />| p_out |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />|     2 | <br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; SELECT @p_out;<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />| p_out |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />|     2 | <br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;-+</p>
<p style="font: normal normal normal 12px/normal song, Verdana;"><strong>INOUT参数例子:</strong></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">mysql&gt; CREATE PROCEDURE sp_demo_inout_parameter(INOUT p_inout INT) BEGIN SELECT p_inout; SET p_inout=2; SELECT p_inout; END; <br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />执行结果:<br style="font: normal normal normal 12px/normal song, Verdana;" />set @p_inout=1<br style="font: normal normal normal 12px/normal song, Verdana;" />call sp_demo_inout_parameter(@p_inout) //<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" />| p_inout |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" />|       1 |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" />| p_inout | <br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" />|       2 |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />select @p_inout;<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />| @p_inout | <br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />| 2        |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" /></p>
<p style="font: normal normal normal 12px/normal song, Verdana;"><strong><span style="text-decoration: underline;">用户变量</span></strong></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">1、  在mysql客户端使用用户变量</p>
<p style="font: normal normal normal 12px/normal song, Verdana;">mysql&gt; SELECT &#8216;Hello World&#8217; into @x;<br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; SELECT @x;<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />| @x          |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />| Hello World |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; SET @y=&#8217;Goodbye Cruel World&#8217;;<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; select @y;<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" />| @y                  |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" />| Goodbye Cruel World |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; SET @z=1+2+3;<br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; select @z;<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" />| @z   |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" />| 6    |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;+<br style="font: normal normal normal 12px/normal song, Verdana;" /></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">2、  在存储过程中使用用户变量</p>
<p style="font: normal normal normal 12px/normal song, Verdana;">mysql&gt; CREATE PROCEDURE GreetWorld(  )  SELECT CONCAT(@greeting,&#8217; World&#8217;);<br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; SET @greeting=&#8217;Hello&#8217;;<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; CALL GreetWorld(  );<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />| CONCAT(@greeting,&#8217; World&#8217;) |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" />| Hello World                |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-+<br style="font: normal normal normal 12px/normal song, Verdana;" /></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">3、  在存储过程间传递全局范围的用户变量</p>
<p style="font: normal normal normal 12px/normal song, Verdana;">mysql&gt; CREATE PROCEDURE p1(  )   SET @last_procedure=&#8217;p1&#8242;;<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; CREATE PROCEDURE p2(  )  SELECT CONCAT(&#8216;Last procedure was &#8216;,@last_procedure);<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; CALL p1(  );<br style="font: normal normal normal 12px/normal song, Verdana;" /> <br style="font: normal normal normal 12px/normal song, Verdana;" />mysql&gt; CALL p2(  );<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;+<br style="font: normal normal normal 12px/normal song, Verdana;" />| CONCAT(&#8216;Last procedure was &#8216;,@last_procedure) |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;+<br style="font: normal normal normal 12px/normal song, Verdana;" />| Last procedure was p1                         |<br style="font: normal normal normal 12px/normal song, Verdana;" />+&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;+<br style="font: normal normal normal 12px/normal song, Verdana;" /></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">注意:</p>
<p style="font: normal normal normal 12px/normal song, Verdana;">①用户变量名一般以@开头</p>
<p style="font: normal normal normal 12px/normal song, Verdana;">②滥用用户变量会导致程序难以理解及管理</p>
<p style="font: normal normal normal 12px/normal song, Verdana;"><strong><span style="text-decoration: underline;">注释</span></strong></p>
<p style="font: normal normal normal 12px/normal song, Verdana;">mysql存储过程可使用两种风格的注释</p>
<p style="font: normal normal normal 12px/normal song, Verdana;">双模杠：&#8211;</p>
<p style="font: normal normal normal 12px/normal song, Verdana;">该风格一般用于单行注释</p>
<p style="font: normal normal normal 12px/normal song, Verdana;">c风格：/* 注释内容 */ 一般用于多行注释</p>
]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2010/05/28/mysql-variable-params-comment/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>数据库的层次结构</title>
		<link>http://fendou.org/2010/03/15/database-hierarchy-structures/</link>
		<comments>http://fendou.org/2010/03/15/database-hierarchy-structures/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 14:01:39 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[读书笔记]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=667</guid>
		<description><![CDATA[1、树状结构 在历史上，层次数据库最早出现，将数据库保存为文件中的记录，各种逻辑被嵌套到一起，而没有将同样的记录按照线性排列。层次数据库对某些查询非常适合，但是过强的结构限制了人们对数据的自由操控，后来出现的网络（CODASYL）数据库，虽然灵活了很多，但数据操控仍然很困难，知道关系型理论的出现，才证明的了数据库设计是科学而不是工艺，然而，因为层次模型很有弹性，所以层次结构依然极为常见（至少层次描述非常常见），例如XML和LDAP等层次技术非常活跃，严格的说HTML也算是一种层次存取数据的方式。 层次式数据不太容易理解，比如ERP系统中最基本的物料单，层次结构之所以复杂，主要原因不是因为组件之间的关系表达，而是访问树的方式，我们访问树的部分或全部节点，通常按照顺序返回这些节点，访问树通常由DBMS引擎以过程性方式实现，而过程性操作正是违背关系理论的主要表现之一。 2、树状结构和主从结构 很多人认为“父子关系”和“主从关系”没有什么不同，实际上这两种关系有着很多的不同。 1） 树状结构保存只需要一个表。代表层次结构的树，其所有节点完全相同，叶子节点的类型有时可能不同，例如文件系统中的文件夹和文件节点，如果撇去这点，所有的节点类型完全相同，我们可以用相同的方法描述，而且同一个表来代表节点，换句话说，表与它本身之间有种主从关系，而不是两个类型不同的表关系。 2）深度。层次结构中，与根节点的距离本身是重要的信息，而在主从关系中，不是主表就是明细表。 3）所有权。主从关系中，可以明确的外键完整性约束，例如，每个表中订单必须与另外一张表的已存在的ID对应，但层次结构，比如，虽然比如经理的工号虽然是参照已经存在的员工的工号规则来的，但是经理向老板报告，不跟员工报告，这会导致NULL值问题。 4）多重父节点。以父节点似乎别数据结合子节点，是假设一个子节点只有一个父节点，实际上生活中，很多情况下都不是这样，比如机械零件和螺丝钉，那就不是树了，父子关系就无能为力了。 其实某位大牛曾经说过：从关系理论角度去理解树的结构，树有两种实体类型，一个是节点，另一个是节点之间的连接。这样的设计世界上是解决了完整性约束的的问题，因为只有实际存在连结的节点才能被描述。这种描述实际上最后能描出一个图来，也就是能解决一个子节点对应多个父节点的问题。 DBMS厂商常常实现了空间数据处理或全文索引等特殊功能，但对层次结构的支持很薄弱或者根本没有。 处理层次结构的主要困难在于树的访问，当然仅仅为了在图形用户界面中显示树状结构，每次用户点击将树展开并没有什么问题]]></description>
			<content:encoded><![CDATA[<p>1、树状结构<br />
在历史上，层次数据库最早出现，将数据库保存为文件中的记录，各种逻辑被嵌套到一起，而没有将同样的记录按照线性排列。层次数据库对某些查询非常适合，但是过强的结构限制了人们对数据的自由操控，后来出现的网络（CODASYL）数据库，虽然灵活了很多，但数据操控仍然很困难，知道关系型理论的出现，才证明的了数据库设计是科学而不是工艺，然而，因为层次模型很有弹性，所以层次结构依然极为常见（至少层次描述非常常见），例如XML和LDAP等层次技术非常活跃，严格的说HTML也算是一种层次存取数据的方式。<br />
层次式数据不太容易理解，比如ERP系统中最基本的物料单，层次结构之所以复杂，主要原因不是因为组件之间的关系表达，而是访问树的方式，我们访问树的部分或全部节点，通常按照顺序返回这些节点，访问树通常由DBMS引擎以过程性方式实现，而过程性操作正是违背关系理论的主要表现之一。<br />
2、树状结构和主从结构<br />
很多人认为“父子关系”和“主从关系”没有什么不同，实际上这两种关系有着很多的不同。<br />
 1） 树状结构保存只需要一个表。代表层次结构的树，其所有节点完全相同，叶子节点的类型有时可能不同，例如文件系统中的文件夹和文件节点，如果撇去这点，所有的节点类型完全相同，我们可以用相同的方法描述，而且同一个表来代表节点，换句话说，表与它本身之间有种主从关系，而不是两个类型不同的表关系。<br />
2）深度。层次结构中，与根节点的距离本身是重要的信息，而在主从关系中，不是主表就是明细表。<br />
3）所有权。主从关系中，可以明确的外键完整性约束，例如，每个表中订单必须与另外一张表的已存在的ID对应，但层次结构，比如，虽然比如经理的工号虽然是参照已经存在的员工的工号规则来的，但是经理向老板报告，不跟员工报告，这会导致NULL值问题。<br />
4）多重父节点。以父节点似乎别数据结合子节点，是假设一个子节点只有一个父节点，实际上生活中，很多情况下都不是这样，比如机械零件和螺丝钉，那就不是树了，父子关系就无能为力了。<br />
其实某位大牛曾经说过：从关系理论角度去理解树的结构，树有两种实体类型，一个是节点，另一个是节点之间的连接。这样的设计世界上是解决了完整性约束的的问题，因为只有实际存在连结的节点才能被描述。这种描述实际上最后能描出一个图来，也就是能解决一个子节点对应多个父节点的问题。<br />
DBMS厂商常常实现了空间数据处理或全文索引等特殊功能，但对层次结构的支持很薄弱或者根本没有。<br />
处理层次结构的主要困难在于树的访问，当然仅仅为了在图形用户界面中显示树状结构，每次用户点击将树展开并没有什么问题 <img src='http://fendou.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2010/03/15/database-hierarchy-structures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

