[{"data":1,"prerenderedAt":89},["ShallowReactive",2],{"blog:\u002Fblog\u002F2015\u002F11\u002F04\u002Funion-and-union-all\u002F":3},{"id":4,"title":5,"body":6,"categories":73,"comments":75,"date":76,"description":77,"draft":78,"extension":79,"legacySlug":80,"meta":81,"navigation":75,"path":82,"seo":83,"stem":84,"tags":85,"updated":87,"__hash__":88},"blog\u002Fblog\u002F2015\u002F11\u002F04\u002Funion-and-union-all.md","union和union all的区别",{"type":7,"value":8,"toc":69},"minimark",[9,16,21,24,27,30,33,36,39,42,45,48,51,54,57,60],[10,11,12],"p",{},[13,14,15],"strong",{},"Union因为要进行重复值扫描，所以效率低。如果合并没有刻意要删除重复行，那么就使用Union All",[10,17,18],{},[13,19,20],{},"两个要联合的SQL语句 字段个数必须一样，而且字段类型要“相容”（一致）；",[10,22,23],{},"如果我们需要将两个select语句的结果作为一个整体显示出来，我们就需要用到union或者union all关键字。union(或称为联合)的作用是将多个结果合并在一起显示出来。",[10,25,26],{},"union和union all的区别是,union会自动压缩多个结果集合中的重复结果，而union all则将所有的结果全部显示出来，不管是不是重复。",[10,28,29],{},"Union：对两个结果集进行并集操作，不包括重复行，同时进行默认规则的排序；",[10,31,32],{},"Union All：对两个结果集进行并集操作，包括重复行，不进行排序；",[10,34,35],{},"Intersect：对两个结果集进行交集操作，不包括重复行，同时进行默认规则的排序；",[10,37,38],{},"Minus：对两个结果集进行差操作，不包括重复行，同时进行默认规则的排序。",[10,40,41],{},"可以在最后一个结果集中指定Order by子句改变排序方式。",[10,43,44],{},"例如：",[10,46,47],{},"select employee_id,job_id from employees\nunion\nselect employee_id,job_id from job_history",[10,49,50],{},"以上将两个表的结果联合在一起。这两个例子会将两个select语句的结果中的重复值进行压缩，也就是结果的数据并不是两条结果的条数的和。如果希望即使重复的结果显示出来可以使用union all,例如：",[10,52,53],{},"在oracle的scott用户中有表emp\nselect * from emp where deptno >= 20\nunion all\nselect * from emp where deptno \u003C= 30\n这里的结果就有很多重复值了。",[10,55,56],{},"有关union和union all关键字需要注意的问题是：",[10,58,59],{},"union 和 union all都可以将多个结果集合并，而不仅仅是两个，你可以将多个结果集串起来。\n使用union和union all必须保证各个select 集合的结果有相同个数的列，并且每个列的类型是一样的。但列名则不一定需要相同，oracle会将第一个结果的列名作为结果集的列名。例如下面是一个例子：\nselect empno,ename from emp\nunion\nselect deptno,dname from dept\n我们没有必要在每一个select结果集中使用order by子句来进行排序，我们可以在最后使用一条order by来对整个结果进行排序。例如：\nselect empno,ename from emp\nunion\nselect deptno,dname from dept\norder by ename;",[10,61,62,63],{},"原文地址：",[64,65,66],"a",{"href":66,"rel":67},"http:\u002F\u002Fwww.cnblogs.com\u002Fxiangshu\u002Farticles\u002F2054447.html",[68],"nofollow",{"title":70,"searchDepth":71,"depth":71,"links":72},"",2,[],[74],"Mysql",true,"2015-11-04 13:20:34","Union因为要进行重复值扫描，所以效率低。如果合并没有刻意要删除重复行，那么就使用Union All 两个要联合的SQL语句 字段个数必须一样，而且字段类型要“相容”（一致）； 如果我们需要将两个select语句的结果作为一个整体显示出来，我们就需要用到union或者union all关键字。un",false,"md","union-and-union-all",{},"\u002Fblog\u002F2015\u002F11\u002F04\u002Funion-and-union-all",{"title":5,"description":77},"blog\u002F2015\u002F11\u002F04\u002Funion-and-union-all",[86],"mysql优化",null,"VnB5ClkiynBFKap-jDmLLastKCeBiMoHw9zDpsTnP38",1783807996125]