join语句

1 等值 join

Hive支持通常的SQL JOIN语句,但是只支持等值连接,==不支持非等值连接==。

案例实操

select * from stu left join score on stu.id = score.s_id;

根据学生和成绩表,查询学生姓名对应的成绩

2 表的别名

好处

  • 使用别名可以简化查询。

  • 使用表名前缀可以提高执行效率。

案例实操:合并老师与课程表

-- hive当中创建course表并加载数据
create table course (c_id string, c_name string, t_id string) 
row format delimited fields terminated by '\t';
​
load data local inpath '/xsluo/install/hivedatas/course.csv' overwrite into table course;
​
select * from teacher t join course c on t.t_id = c.t_id;

3 内连接 inner join

内连接:只有进行连接的两个表中都存在与连接条件相匹配的数据才会被保留下来。

  • join默认是inner join

案例实操

select * from teacher t inner join course c  on t.t_id = c.t_id;

4 左外连接 left outer join

左外连接:

  • join操作符==左边表中==符合where子句的所有记录将会被返回。

  • 右边表的指定字段没有符合条件的值的话,那么就使用null值替代。

案例实操:查询老师对应的课程

select * from teacher t left outer join course c on t.t_id = c.t_id;

5 右外连接 right outer join

右外连接:

  • join操作符==右边表中==符合where子句的所有记录将会被返回。

  • 左边表的指定字段没有符合条件的值的话,那么就使用null值替代。

案例实操

select * from teacher t right outer join course c on t.t_id = c.t_id;

6 满外连接 full outer join

满外连接:

  • 将会返回==所有表中==符合where语句条件的所有记录。

  • 如果任一表的指定字段没有符合条件的值的话,那么就使用null值替代。

案例实操

select * from teacher t full outer join course c on t.t_id = c.t_id;

7 多表连接

多个表使用join进行连接

==注意:==连接 n个表,至少需要n-1个连接条件。例如:连接三个表,至少需要两个连接条件。

案例实操

select * from teacher t 
left join course c on t.t_id = c.t_id 
left join score s on c.c_id = s.c_id 
left join stu on s.s_id = stu.id;

多表连接查询,查询老师对应的课程,以及对应的分数,对应的学生

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐