Hive使用详解
Hive Join
1 | Hive 只支持等值连接(equality joins)、外连接(outer joins)和(left/right joins)。 |
准备a.txt、b.txt、c.txt,表中字段默认’\t’分隔
1 | [root@node1 hive-1.2.1]# vi a.txt |

1 | a.txt |

1 | b.txt |

1 | c.txt |

在hive中创建a、b、c三张测试表,其中id代表学生的学号,name是学生姓名,score是学生成绩,book是学生拥有的书
1 | 三张表中,id都是主键 |
1 | hive> create table a( |
1 | hive> create table b( |
1 | hive> create table c( |
将a.txt、b.txt、c.txt文件中的数据导入a、b、c表中
1 | hive> load data local inpath 'a.txt' into table a; |

join的用法:
1 | 找出班级中参加了某种考试的学生姓名以及成绩。该需求希望做到的是,取表a和表b中均存在的记录,并使用主键id连结起来 |
1 | hive> create table d as select a1.id as id_a, a1.name , b1.id as id_b , b1.score |

输出结果:
1 | hive> select * from d; |

如果关联的结果有重复记录,那么记录会全部保留
查询班级中拥有书的同学姓名以及其拥有的书名
1 | hive> create table e as select a1.id as id_a, a1.name , c1.id as id_c , c1.book |

输出结果:
1 | hive> select * from e; |

只查询班级中拥有书的同学:
1 | hive> create table f as select a1.id as id_a, a1.name |

输出结果:
1 | hive> select * from f; |

发现:
1 | 结果集每个id保留了2条记录,有些数据是重复的,我们只需要保留1条就足够了,这时可以使用distinct对关联结果进行去重 |
可以使用distinct去重
1 | hive> create table g as select distinct a1.id as id_a, a1.name |

输出结果:
1 | hive> select * from g; |

Left outer join的使用
1 | 现在需求: |
1 | hive> create table h as select distinct a1.id as id_a, a1.name, b1.id as id_b , b1.score |

输出结果
1 | hive> select * from h; |

1 | 在结果集中,如果某学生没有参加某考试,即其在b表中无相应记录,那么结果集的相应字段会被赋予NULL值 |
1 | hive> create table i as select distinct a1.id as id_a, a1.name, b1.id as id_b , b1.score |

输出结果
1 | hive> select * from i; |
1 | 上述代码加上where b.id is not null,把在b表中值为空的记录删除,实现的其实就是传统sql中的exists in操作 |

需求:把班级里未参加考试的学生取出来,因为我们要通知它们补考。这个需求即取出a中存在但b中不存在的记录
1 | hive> create table j as select distinct a1.id as id_a, a1.name, b1.id as id_b , b1.score |

输出结果:
1 | hive> select * from i; |
1 | 实现的其实就是传统sql中的exists not in操作, |

Left semi join
1 | left semi join,有一个限制条件,即右表的字段只能出现在on子句中,而不能在select和where字句中引用 |
需求:找出班级中参加考试的学生
1 | hive> create table k as select distinct a1.id ,a1.name from a a1 |

输出结果:
1 | hive> select * from k; |

full outer join用法
1 | full outer join实现全连接。 |
需求:取出班级中全体学生/参加考试的学生及其成绩。即取a中存在或b中存在的记录
1 | hive> create table l as select distinct a1.id ,a1.name , b1.id as id_b ,b1.score |

输出结果:
1 | hive> select * from l; |

1 | left outer join where is not null与left semi join的联系与区别: |
本文作者 : Matrix
原文链接 : https://matrixsparse.github.io/2016/02/12/Hive的使用详解/
版权声明 : 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!
知识 & 情怀 | 二者兼得