连接方式可以分为一下几种
等值连接和不等值连接需要使用到的数据和表
--emp表-------------------------
create table emp(
deptno int, id int,
name string, sal int
)row format delimited fields terminated by ','
--salg表----------------------------------
create table salg(
deptno int,
deptname string,
salgrade string )
row format delimited fields terminated by ','
--grade表-----------------------------------------
create table grade(
slow int,
shig int,
sgrade string
)row format delimited fields terminated by ','
--emp表数据-----------------------------------
1,01,jack,10000
2,02,monky,8000
3,03,lucy,7000
4,02,bob,5000
5,04,李三,6000
--salg表数据-------------------------------
01,天安门,num_one
02,南天门,num_two
03,老九门,num_three
--grade表数据-------------------------------------
6000,10000,num_one
5000,5999,num_two
3000,4999,num_four
等值连接的代码
-- 等值连接
select e.id,e.name,e.sal,s.deptname from emp e,salg s where e.deptno = s.deptno
运行结果:
不等值连接
-- 不等值连接
select e.id ,e.name ,e.sal,g.sgrade from emp e,grade g where e.sal between g.slow and g.shig
运行结果:
外连接用到的表和数据如下:
建立表
english:
create table english(
id bigint,
name string,
price int
)row format delimited fields terminated by ' ';
建立表chinese:
create table chinese(
ename string,
cname string
)row format delimited fields terminated by ' ';
表数据:
english表
10001 pen 99
10002 orange 77
10003 apple 80
10001 ruler 50
10004 banana 100
chinese表:
apple 苹果
orange 橘子
banana 香蕉
ruler 尺子
左外连接:
-- 左外连接
【left】join
select * from english left join chinese on english.name=chinese.ename;
-- 右外链接【right】join
select * from english right join chinese on english.name=chinese.ename;
左外连接运行结果如图:
其他结果就不一一展示
值得一说的是
Hive中使用semi join替代exist in加一个子查询
使用例句:
select * from english left semi join chinese on english.name=chinese.ename;
-- 该代码等价于
select * from english exist in ( select * from english where english.name = chinese.name)
-- 但是在hive中这么写时不可以的,要用semi join