<h2 >mysql&nbsp;中合并查询结果union用法&nbsp;or、in与union&nbsp;all&nbsp;的查询效率</h2>
		
				<span class="img2">
			<img width="15" height="15" align="absmiddle" title="此博文包含图片" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" class="SG_icon SG_icon18">	
		</span>
				<span class="time SG_txtc">(2016-05-09 11:18:23)</span><div class="turnBoxzz"><a href="javascript:;" class="SG_aBtn SG_aBtn_ico SG_turn" action-type="reblog" action-data="{srcBlog:1, blogId:'13088c10a0102wq5c'}"><cite><img class="SG_icon SG_icon111" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" width="15" height="15" align="absmiddle">转载<em class="arrow">▼</em></cite></a></div>		</div>
	<div class="articalTag" >
		<table>
			<tbody><tr>
				<td class="blog_tag">
				<script>
				var $tag='mysql,union,or,in';
				var $tag_code='dfc4c67d981830b93087c8132a78c03b';
				var $r_quote_bligid='13088c10a0102wq5c';
				var $worldcup='0';
				var $worldcupball='0';
				</script>
										<span class="SG_txtb">标签:</span>
																			<h3><a href="http://search.sina.com.cn/?c=blog&amp;q=mysql&amp;by=tag" target="_blank">mysql</a></h3>
																			<h3><a href="http://search.sina.com.cn/?c=blog&amp;q=union&amp;by=tag" target="_blank">union</a></h3>
																			<h3><a href="http://search.sina.com.cn/?c=blog&amp;q=or&amp;by=tag" target="_blank">or</a></h3>
																			<h3><a href="http://search.sina.com.cn/?c=blog&amp;q=in&amp;by=tag" target="_blank">in</a></h3>
															</td>
				<td class="blog_class">
										<span class="SG_txtb">分类:</span>
					<a target="_blank" href="http://blog.sina.com.cn/s/articlelist_5109235978_5_1.html">mysql</a>
									</td>
			</tr>
		</tbody></table>
	</div>
					<!-- 正文开始 -->
	<div >
		<p style="margin: 0px; line-height: 28px; padding: 0px 0px 15px; widows: 2; font-stretch: normal; font-family: 宋体, 'Arial narrow', arial, serif; orphans: 2; background-color: rgb(255, 255, 255);">

问题一 mysql
中合并查询结果union用法

今天来写写union的用法及一些需要注意的。

 union:联合的意思,即把两次或多次查询结果合并起来。

 要求:两次查询的列数必须一致

 推荐:列的类型可以不一样,但推荐查询的每一列,想对应的类型以一样

 可以来自多张表的数据:多次sql语句取出的列名可以不一致,此时以第一个sql语句的列名为准。

 如果不同的语句中取出的行,有完全相同(这里表示的是每个列的值都相同),那么union会将相同的行合并,最终只保留一行。也可以这样理解,union会去掉重复的行。

如果不想去掉重复的行,可以使用union all。

 如果子句中有order by,limit,需用括号()包起来。推荐放到所有子句之后,即对最终合并的结果来排序或筛选。

如:(select * from a order by id) union (select * from b order id);

在子句中,order by 需要配合limit使用才有意义。如果不配合limit使用,会被语法分析器优化分析时去除。


问题二 OR、in和union all 查询效率到底哪个快。

OR、in和union all 查询效率到底哪个快。

网上很多的声音都是说union all 快于 or、in,因为or、in会导致全表扫描,他们给出了很多的实例。

但真的union all真的快于or、in?本文就是采用实际的实例来探讨到底是它们之间的效率。

1:创建表,插入数据、数据量为1千万【要不效果不明显】。

  1. drop table if EXISTS BT;  
  2. create table BT(  
  3.     ID int(10) NOT NUll 
  4.     VName varchar(20) DEFAULT '' NOT NULL 
  5.     PRIMARY keyID  
  6. )ENGINE=INNODB;  

 该表只有两个字段 ID为主键【索引页类似】,一个是普通的字段。(偷懒就用简单的表结构呢)

向BT表中插入1千万条数据

这里我写了一个简单的存储过程【所以你的mysql版本至少大于5.0,俺的版本为5.1】,代码如下。

注意:最好

    INSERT INTO BT ( ID,VNAME )  VALUES( i, CONCAT( 'M', i ) );---1

    修改为

   INSERT INTO BT ( ID,VNAME )  VALUES( i, CONCAT( 'M', i, 'TT' ) );---2

   修改原因在

   非索引列及VNAME使用了联合进行完全扫描请使用1 

   非索引列及VNAME使用了全表扫描请使用2 

 

  1. DROP PROCEDURE IF EXISTS test_proc;  
  2. CREATE PROCEDURE test_proc()  
  3. BEGIN  
  4. declare int default 0;  
  5. set autocommit 0;  
  6. while i<10000000 do  
  7. INSERT INTO BT ID,VNAME  VALUESi, CONCAT( 'M');  
  8. set i+1;  
  9. if i 00 then  
  10. commit 
  11. end if;  
  12. end while;  
  13. END 

 就不写注释呢,挺简单的。

存储过程是最好设置下innob的相关参数【主要和日志、写缓存相关这样能加快插入】,俺没有设置插入1千万条数据插了6分钟。

部分数据如下:1千万数据类似

mysql 中合并查询结果union用法 or、in与union all 的查询效率

2:实战

    2.1 :分别在索引列上使用 or、in、union all

           我们创建的表只有主键索引,所以只能用ID做查询呢。我们查 ID 为 98,85220,9888589的三个数据各个耗时如下:

mysql 中合并查询结果union用法 or、in与union all 的查询效率

 时间都为0.00,怎么会这样呢,呵呵所有查询都是在毫秒级别。

我使用其他的工具--EMS SQL Manager  for mysql

查询显示时间为

93 ms, 94ms,93 ms,时间相差了多少几乎可以忽略。

然后我们在看看各自的执行计划

mysql 中合并查询结果union用法 or、in与union all 的查询效率

这里要注意的字段type 与ref字段

我们发现union all 的所用的 type【type为显示连接使用了何种类型】 为ref 而or和in为range【ref连接类型优于range,相差不了多少】,而查询行数都一样【看rows字段都是为3】。

从整个的过程来看,在索引列使用常数or及in和union all查询相差不了多少。

但为什么在有的复杂查询中,再索引列使用or及in 比union all 速度慢很多呢,这可能是你的查询写的不够合理,让mysql放弃索引而进行全表扫描。

2.2:在非索引列中使用 or、in及union all。

    我们查 VNAME 为 M98,M85220,M9888589的三个数据各个耗时如下:

mysql 中合并查询结果union用法 or、in与union all 的查询效率

我们发现为啥union all查询时间几乎为 or 和in的三倍。

这是为什么呢,我们先不说,先看看三个的查询计划。

mysql 中合并查询结果union用法 or、in与union all 的查询效率

这里我们发现计划几乎一样。

但我们要注意扫描的此时对于 or及in 来说 只对表扫描一次即rows是列为9664782。

而对于union all 来说对表扫描了三次即rows的和为9664782*3。

这也是为什么我们看到union all 为几乎为三倍的原因。

备注: 如果使用存储过程使用第二sql该执行计划所有的type列 为 all,其实这个是我最想演示的,但现在已经快写完毕了才发现问题将错就错呢。

3:总结

     3.1:不要迷信union all 就比 or及in 快,要结合实际情况分析到底使用哪种情况。

     3.2:对于索引列来最好使用union all,因复杂的查询【包含运算等】将使or、in放弃索引而全表扫描,除非你能确定or、in会使用索引。

    3.3:对于只有非索引字段来说你就老老实实的用or 或者in,因为 非索引字段本来要全表扫描而union all 只成倍增加表扫描的次数。

    3.4:对于及有索引字段【索引字段有效】又包含非索引字段来时,按理你也使用or 、in或者union all 都可以,

       但是我推荐使用or、in。

      如以下查询:

  1. select from bt where bt.VName 'M98' or bt.id ='9888589'  
  2.   
  3. select from bt where bt.VName 'M98'  
  4. UNION ALL  
  5. select from bt where  bt.id '9888589'  

     该两个查询速度相差多少 主要取决于 索引列查询时长,如索引列查询时间太长的话,那你也用or或者in代替吧。

 

   3.5: 以上主要针对的是单表,而多表联合查询来说,考虑的地方就比较多了,比如连接方式,查询表数据量分布、索引等,再结合单表的策略选择合适的关键字。  

2

0

        </div>
        <div class="clearit"></div>
	</div>
	<div class="articalInfo">
		<!-- 分享到微博 {$t_blog} -->
		<div class="IL">
			阅读<span >┊</em> 
			<a href="#commonComment">评论</a> <span >(0)</span>
			<em class="SG_txtb">┊</em><a href="#" >┊</em>
			<a onclick="return false;" href="javascript:;"><cite ><b>▼</b></a>
								<em class="SG_txtb">┊</em><a href="http://blog.sina.com.cn/main_v5/ria/print.html?blog_id=blog_13088c10a0102wq5c" target="_blank">打印</a><em class="SG_txtb">┊</em><a >举报</a>
										</div>
		<div class="IR">
			<table>
				<tbody><tr>
										<th class="SG_txtb" scope="row">已投稿到:</th>
					<td>
						<div class="IR_list">
							<span><img class="SG_icon SG_icon36" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" width="15" height="15" title="排行榜" align="absmiddle"> <a href="http://blog.sina.com.cn/lm/114/117/day.html" class="SG_linkb" target="_blank">排行榜</a></span>							</div>
					</td>
									</tr>
								</tbody></table>
		</div>
	</div>
	<div class="clearit"></div>
	<div class="blogzz_zzlist borderc" ></div></div>
	<div class="articalfrontback SG_j_linedot1 clearfix" >
						<div><span class="SG_txtb">前一篇:</span><a href="http://blog.sina.com.cn/s/blog_13088c10a0102wpzo.html">msyql&nbsp;百分比表示,mysql&nbsp;表示null,mysql将一张表的查询结果存到另一张表中</a></div>
									<div><span class="SG_txtb">后一篇:</span><a href="http://blog.sina.com.cn/s/blog_13088c10a0102wq8v.html">MySQL中distinct和group&nbsp;by性能比较</a></div>
				</div>
	<div class="clearit"></div>
						
	<div ></div>
			<div class="allComm">
		<div class="allCommTit">
			<div class="SG_floatL">
			    <strong>评论</strong>
			    <span >
			        <span style="margin-left:15px; width:220px; display:inline-block;"><a target="_blank" href="http://blog.sina.com.cn/lm/8/2009/0325/105340.html">重要提示:警惕虚假中奖信息</a></span>
			    </span>
			</div>
			<div class="SG_floatR"><a class="CP_a_fuc" href="#post">[<cite>发评论</cite>]</a></div>
		</div>
		<ul >抢沙发&gt;&gt;</a></span></div></li></ul>
		<div class="clearit"></div>
		<div class="myCommPages SG_j_linedot1" style="display: none;">
			<div class="SG_page" >点击加载更多</a></div>
			<div class="clearit"></div>
		</div>
		<a name="post"></a>
		<div class="writeComm">
			<div class="allCommTit">
				<div class="SG_floatL">
				    <strong>发评论</strong>
				    <span></span>
				</div>
				<div class="SG_floatR"></div>
			</div>
			<div class="wrCommTit">
				<div class="SG_floatL" ></div>
			</div>
			<div class="formTextarea">
				<div style="float:left;" >
				<iframe border:1px solid #C7C7C7;
	height:158px;width:448px;maring-top:1px;background-color:white;" src="http://blog.sina.com.cn/main_v5/ria/blank2.html"></iframe>
				<textarea ></textarea>
				</div>
				<div >
					<textarea ></textarea>
				</div>
				<div class="faceblk" >
					<div >
					<div class="facestyle" ></div></div>
					<ul ></a></li></ul>
				</div>
				<div class="clearit"></div>
			</div>
			<div class="formLogin">
				<div class="SG_floatL"> 
				<p ></p>
				<p ></p>
				</div>

				<span style="display: none; color: rgb(153, 153, 153); margin-left: 10px;" ></span>

										<!--<div class="SG_floatR" >匿名评论</label></div>-->
								</div>
			<div class="formBtn">
				<a href="javascript:;" onclick="return false;" class="SG_aBtn" tabindex="5"><cite >发评论</cite></a>
				<p class="SG_txtc">以上网友发言只代表其个人观点,不代表新浪网的观点或立场。</p>
			</div>
		</div>
	</div>
			<div class="clearit"></div>
	
			<div class="articalfrontback articalfrontback2 clearfix">
					  <div class="SG_floatL"><span class="SG_txtb">&lt;&nbsp;前一篇</span><a href="http://blog.sina.com.cn/s/blog_13088c10a0102wpzo.html">msyql&nbsp;百分比表示,mysql&nbsp;表示null,mysql将一张表的查询结果存到另一张表中</a></div>
								  <div class="SG_floatR"><span class="SG_txtb">后一篇&nbsp;&gt;</span><a href="http://blog.sina.com.cn/s/blog_13088c10a0102wq8v.html">MySQL中distinct和group&nbsp;by性能比较</a></div>
				</div>
	<div class="clearit"></div>
			
</div>

相关文章: