union all和union都 可以把两张表连起来,union 会排除重复的记录union all 不会排除重复的记录 。不同于join,join为笛卡儿积。
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
---------------------------------------------------------------
![union all和union的用法 hive union all用法](http://img.aihuau.com/images/31101031/31070425t01d80181f60c217c09.png)
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 不会排除重复的记录记录