UNION 和UNION ALL两者之间的内在区别

来源:互联网 发布:淘宝半实体娃娃的真假 编辑:程序博客网 时间:2024/05/01 23:48

在数据库中,UNION和UNION ALL关键字都是将两个结果集合并为一个,但这两者从使用和效率上来说都有所不同。

UNION在进行表链接后会筛选掉重复的记录,所以在表链接后会对所产生的结果集进行排序运算,删除重复的记录再返回结果。

实际大部分应用中是不会产生重复的记录,最常见的是过程表与历史表UNION。如:

 

select * from gc_dfys 

union

select * from ls_jg_dfys

 

这个SQL在运行时先取出两个表的结果,再用排序空间进行排序删除重复的记录,最后返回结果集,如果表数据量大的话可能会导致用磁盘进行排序。

 

而UNION ALL只是简单的将两个结果合并后就返回。这样,如果返回的两个结果集中有重复的数据,那么返回的结果集就会包含重复的数据了。

 

从效率上说,UNION ALL 要比UNION快很多,所以,如果可以确认合并的两个结果集中不包含重复的数据的话,那么就使用UNION ALL,如下:

 

select * from gc_dfys 

union all

select * from ls_jg_dfys
<script type="text/javascript">&lt;!--google_ad_client = &quot;pub-1295960146753136&quot;;google_ad_width = 300;google_ad_height = 250;google_ad_format = &quot;300x250_as&quot;;google_ad_type = &quot;text_image&quot;;google_ad_channel = &quot;&quot;;google_ui_features = &quot;rc:6&quot;;//--&gt;</script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script><script src="http://pagead2.googlesyndication.com/pagead/expansion_embed.js"></script><script src="http://googleads.g.doubleclick.net/pagead/test_domain.js"></script><script>google_protectAndRun(&quot;ads_core.google_render_ad&quot;, google_handleError, google_render_ad);</script>

原创粉丝点击