Oracle中union和union all用法及区别

今天项目中sql语句使用到了union,在此总结一下union和union all的用法。

union可以将两个sql语句的查询结果合并起来,但前提是两个sql语句产生的结果的数据类型应该是一致的,否则这条sql语句是不对的。同时union所产生的结果是经过dinstinct的,也就是会去除重复的结果值。

而union all 也是将两个sql语句的查询结果合并起来,但是与union不同的是不会去除重复的结果值。

如下:

select count(*) from t_yh yh where yh.scbj=0

 查询结果为:76

select count(*) from t_fj fj where fj.scbj=0 

查询结果也为:76

综合以上两条sql语句,将第一条和第二条用union连接起来:

select count(*) from t_yh yh where yh.scbj=0
union
select count(*) from t_fj fj where fj.scbj=0 

 所产生的结果:

使用union all 将第一条和第二条连接起来:

select count(*) from t_yh yh where yh.scbj=0
union all
select count(*) from t_fj fj where fj.scbj=0 

所产生的结果:

 
 另外注意以下语句:

select count(*) from t_yh yh where yh.scbj=0
union
select max(fj.id) from t_fj fj where fj.scbj=0 

 这条语句是不正确的,因为数据类型不一致:



 所以要进行数据类型转换:

如下:

select count(*) from t_yh yh where yh.scbj=0
union
select to_number(max(fj.id)) from t_fj fj where fj.scbj=0 

 此时该条语句就可以正确执行了,执行结果:



 

猜你喜欢

转载自lilixu.iteye.com/blog/2094696