日期:2014-05-16  浏览次数:20361 次

UNION 和 UNION ALL 的用法

UNION 指令的目的是将两个 SQL 语句的结果合并起来,可以查看你要的查询结果.?

例如:?
select cpid from eps_cp union select cpid from eps_cpcms_user?

union用法中,两个select语句的字段类型匹配,而且字段个数要相同?
select cpid ,ISAVAILABLE from eps_cp union all select cpid,eps_cpcms_user.isadmin? from eps_cpcms_user?

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

在查询中会遇到 UNION ALL,它的用法和union一样,只不过union含有distinct的功能,它会把两张表了重复的记录去掉,而union all不会,所以从效率上,union all 会高一点,但在实际中用到的并不是很多.?
UNION ALL只是简单的将两个结果合并后就返回。这样,如果返回的两个结果集中有重复的数据,那么返回的结果集就会包含重复的数据了。?
从效率上说,UNION ALL 要比UNION快很多,所以,如果可以确认合并的两个结果集中不包含重复的数据的话,那么就使用UNION ALL?
尽量使用union all,因为union需要进行排序,去除重复记录,效率低

?

--合并重复行

select * from A

union

select * from B

?

?

--不合并重复行

select * from A

union all

select * from B

?

?

按某个字段排序

--合并重复行

select *

from (

select * from A

union

select * from B) AS T

order by 字段名

?

--不合并重复行

select *

from (

select * from A

union all

select * from B) AS T

order by 字段名

?

//sql server