union/union all的用法

来源:互联网 发布:14总决赛詹姆斯数据 编辑:程序博客网 时间:2024/03/29 04:06

请看一下一个查询的问题  
我有两张表  
tab1  
       字段  
       aID  
       bID  
 
tab2  
       字段  
       aID  
       bID  


tab1中有记录:  
aID    bID  
as1    19  
as2    19  
as3    23  
as4    45  
tab2中有记录:  
aID    bID  
as2    19  
as3    19  
as4    19  


现在需要查找出两张表中bID相等的且bID=19的记录,应该是5条记录  
我用的方法是:  
方法1:select  tab1.aID,tab2.aID  from  tab1,tab2  where  tab1.bID=tab2.bID  and  tab2.bID=19  
方法2:select  tab1.aID,tab2.aID  from  tab1  join  tab2  on  tab1.bID=tab2.bID  where  tab1.bID=19  
上面两中方法选出的记录都是6条,为什么出这样的问题,应该怎么做呢?  
---------------------------------------------------------------  
 
select  *  form  tab1  where  bID=19  
union  all    
select  *  form  tab2  where  bID=19  
 
 
---------------------------------------------------------------  
 
create  table  tab1  
       (aID  char(10),  
       bID  char(10))  
go  
 
insert  into  tab1(aid,bid)  values('as1','19')  
insert  tab1  values('as2','19')  
insert  tab1  values('as3','38')  
insert  tab1  values('as4','45')  
go  
create  table  tab2  
       (aID  char(10),  
       bID  char(10))  
go  
go  
insert  tab2  values('as2','19')  
insert  tab2  values('as3','19')  
insert  tab2  values('as4','19')  
go  
select  *  from  tab1  
 
select  *  from  tab1  where  tab1.bid='19'union  all  select  *  from  tab2    where  tab2.bid='19'  
 
 
斑竹加的话:  
1、join  产生的是笛卡尔积。  
2、union  会排除重复的记录  
3、union  all  不会排除重复的记录  
 

 

union子句
union操作符将两个查询结果合并为一个结果集。为连接查询合并两个表时:列的数日和顺序在查中必须一致;数据类型兼容
语法:
select  语句
union   [ all ]
select  语句
注意:
1 .union运算从最终结果集中删除重复记录,如想不删除重复记录使用all关键字
2 .第一个select语句中不能用order by或compute子句,只能是最后一个select语名后用

例:查询计算机系的学生式年龄不大于19岁的学习,按年龄倒排序
select   *   from  department  where  dept = ' computer ' ;
union ;
 select 
*   from  student  where  age <= 19
order   by  age  desc

原创粉丝点击