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


    							<h2 id="t_13088c10a0102wq5c" class="titName SG_txta">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" id="sina_keyword_ad_area">
    		<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 id="sina_keyword_ad_area2" class="articalContent   newfont_family">
    		<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千万数据类似

    2:实战

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

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

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

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

    查询显示时间为

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

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

    这里要注意的字段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的三个数据各个耗时如下:

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

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

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

    但我们要注意扫描的此时对于 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 id="r_13088c10a0102wq5c" class="SG_txtb">(1906)</span><em class="SG_txtb">┊</em> 
    			<a href="#commonComment">评论</a> <span id="c_13088c10a0102wq5c" class="SG_txtb">(0)</span><em class="SG_txtb">┊</em>				<a href="javascript:;" onclick="$articleManage('13088c10a0102wq5c',5);return false;">收藏</a><span id="f_13088c10a0102wq5c" class="SG_txtb">(0)</span>
    			<em class="SG_txtb">┊</em><a href="#" id="quote_set_sign" onclick="return false ;">转载</a><a href="#" id="z_13088c10a0102wq5c" onclick="return false ;" class="zznum">(0)</a>				<span id="fn_mysql&nbsp;中合并查询结果union用法&nbsp;or、in与union&nbsp;all&nbsp;的查询效率" class="SG_txtb"></span><em class="SG_txtb">┊</em>
    			<a onclick="return false;" href="javascript:;"><cite id="d1_digg_13088c10a0102wq5c">喜欢</cite></a><a id="d1_digg_down_13088c10a0102wq5c" href="javascript:;"><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 id="q_13088c10a0102wq5c" onclick="report('13088c10a0102wq5c');return false;" href="#">举报</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" id="blog_quote" style="display:none"><h3><a href="#" onclick="return false" title="关闭" id="ql_close13088c10a0102wq5c" class="blogzz_closepic SG_floatR"></a>转载列表:</h3>                <ul class="ul_zzlist" id="ql_content13088c10a0102wq5c">                </ul>				<ul style="display:none"><li id="ql_tip13088c10a0102wq5c"></li></ul>                <div class="SG_clearB"></div>                <div class="blogzz_btn">					<a id="btnArticleQuote13088c10a0102wq5c" href="#" onclick="scope.article_quote &amp;&amp; scope.article_quote.check('13088c10a0102wq5c');return false;" class="SG_aBtn SG_aBtn_ico SG_turn"><cite><img class="SG_icon SG_icon111" id="quoteList_quote13088c10a0102wq5c" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" width="15" height="15" align="absmiddle">转载</cite></a>					<p id="quoteDescription13088c10a0102wq5c" class="SG_turntxt" style="display: none;">转载是分享博文的一种常用方式...</p>				</div>				<div id="ql_page13088c10a0102wq5c" class="blogzz_paged"></div>				<div class="clearit"></div></div>
    	<div class="articalfrontback SG_j_linedot1 clearfix" id="new_nextprev_13088c10a0102wq5c">
    						<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 id="loginFollow"></div>
    			<div class="allComm">
    		<div class="allCommTit">
    			<div class="SG_floatL">
    			    <strong>评论</strong>
    			    <span id="commAd_1" style="display: inline-block;">
    			        <span style="margin-left:15px; 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 id="article_comment_list" class="SG_cmp_revert"><li><div class="noCommdate"><span class="SG_txtb">做第一个评论者吧! <img class="SG_icon SG_icon134" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" width="18" height="18" title="" align="absmiddle"><a href="#post">抢沙发&gt;&gt;</a></span></div></li></ul>
    		<div class="clearit"></div>
    		<div class="myCommPages SG_j_linedot1" style="display: none;">
    			<div class="SG_page" id="commentPaging" style="display: none; text-align: center;"><a href="javascript:void(0);" style="">点击加载更多</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" id="commentNick" style="display:none;"></div>
    			</div>
    			<div class="formTextarea">
    				<div style="float:left;" id="commonComment">
    				<iframe id="postCommentIframe" frameborder="0" style="border:1px solid #C7C7C7;
    	height:158px;448px;maring-top:1px;background-color:white;" src="http://blog.sina.com.cn/main_v5/ria/blank2.html"></iframe>
    				<textarea id="commentArea" tabindex="1" style="display:none;"></textarea>
    				</div>
    				<div id="mobileComment" style="float:left;display:none;">
    					<textarea id="mbCommentTa" style="438px;height:150px;border:1px solid #C7C7C7;line-height:18px;padding:5px;"></textarea>
    				</div>
    				<div class="faceblk" id="faceWrap">
    					<div id="smilesSortShow" class="faceline1">
    					<div class="facestyle" id="recomm_1522746653157"><a href="#" key="302"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/302-25.gif" alt="小新小浪" title="小新小浪"></a><a href="#" key="308"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/308-25.gif" alt="炮炮兵" title="炮炮兵"></a><a href="#" key="315"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/315-25.gif" alt="张富贵" title="张富贵"></a><a href="#" key="316"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/316-25.gif" alt="旺狗" title="旺狗"></a><a href="#" key="331"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/331-25.gif" alt="悠嘻猴" title="悠嘻猴"></a><a href="#" key="351"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/351-25.gif" alt="酷巴熊" title="酷巴熊"></a></div><span class="SG_more"><a href="#">更多&gt;&gt;</a></span><div class="clearit"></div></div>
    					<ul id="smilesRecommended" class="faceline01"><li><a href="#"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0321EN00SIGT.gif" alt="就不买你" title="就不买你" height="50" width="50"></a></li><li><a href="#"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0320EN00SIGT.gif" alt="股市" title="股市" height="50" width="50"></a></li><li><a href="#"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0319EN00SIGT.gif" alt="发霉" title="发霉" height="50" width="50"></a></li><li><a href="#"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0318EN00SIGT.gif" alt="陈水边" title="陈水边" height="50" width="50"></a></li><li><a href="#"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0317EN00SIGT.gif" alt="裁员" title="裁员" height="50" width="50"></a></li><li><a href="#"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0316EN00SIGT.gif" alt="音乐" title="音乐" height="50" width="50"></a></li><li><a href="#"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0315EN00SIGT.gif" alt="贴你" title="贴你" height="50" width="50"></a></li><li><a href="#"><img src="http://www.sinaimg.cn/uc/myshow/blog/misc/gif/E___0314EN00SIGT.gif" alt="抢车位" title="抢车位" height="50" width="50"></a></li></ul>
    				</div>
    				<div class="clearit"></div>
    			</div>
    			<div class="formLogin">
    				<div class="SG_floatL"> 
    				<p id="commentlogin" style="display: block;"><span>登录名:</span><input type="text" style=" 115px;" id="login_name" tabindex="2">   <span>密码:</span><input type="password" style=" 115px;" id="login_pass" tabindex="3">   <a href="https://login.sina.com.cn/getpass.html" target="_blank">找回密码</a>   <a href="https://login.sina.com.cn/signup/signup.php?entry=blog&amp;src=blogicp&amp;srcuid=5109235978" target="_blank">注册</a>	<input type="checkbox" id="login_remember"><label for="login_remember" style="display:inline-block;" title="建议在网吧/公用电脑上取消该选项">记住登录状态</label></p><p id="commentloginM" style="display:none;"><span>昵&nbsp;&nbsp;&nbsp;称:</span><input type="text" style=" 115px;" id="comment_anonyous" value="新浪网友" tabindex="2" disabled=""></p><p id="quote_comment_p"><!--<input type="checkbox" id="bb"> <label for="bb"><img height="18" align="absmiddle" width="18" title="" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" class="SG_icon SG_icon110">分享到微博 <img height="15" align="absmiddle" width="15" title="新" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" class="SG_icon SG_icon11"></label>&nbsp;&nbsp;&nbsp;--><input type="checkbox" id="cbCommentQuote"><label for="cbCommentQuote">评论并转载此博文</label><img class="SG_icon SG_icon11" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" width="15" height="15" title="新" align="absmiddle"></p>
    				<p id="geetest-box"></p>
    				</div>
    
    				<span style="display: none; color: rgb(153, 153, 153); margin-left: 10px;" id="login_remember_caution"></span>
    
    										<!--<div class="SG_floatR" id="anonymity_cont"><input type="checkbox" id="anonymity"/><label for="anonymity">匿名评论</label></div>-->
    								</div>
    			<div class="formBtn">
    				<a href="javascript:;" onclick="return false;" class="SG_aBtn" tabindex="5"><cite id="postcommentid">发评论</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>
  • 相关阅读:
    #ifdef的用法
    修改WordPress中上传附件2M大小限制的方法/php+iis上传附件默认大小修改方法
    没有找到libufun.lib,因此这个应用程序未能启动。重新安装应用程序可能会修复此问题。
    JAVA安卓和C# 3DES加密解密的兼容性问题
    使用 Repeater 控件,每隔N条数据输出另外的格式
    Forms表单登陆,动态获取web.config里面的cookies配置
    SQL Server中索引使用及维护
    动态绑定easyui datagrid列名
    Spring Hibernate多数据源配置
    SSH异常处理
  • 原文地址:https://www.cnblogs.com/jpfss/p/8709707.html
Copyright © 2020-2023  润新知