暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Hive join总结

细说数据 2021-06-28
3606

1、温馨提示:本篇内容1200字,阅读全篇大约需要10分钟。


这期给大家介绍一下Hive join的知识。
SQL (Structured Query Language)结构化查询语言,是一种特定目的编程语言,用于管理关系数据库管理系统,或在关系流数据管理系统中进行流处理。
Hive是基于Hadoop的一个数据仓库工具,用来进行数据提取、转化、加载,这是一种可以存储、查询和分析存储在Hadoop中的大规模数据的机制。Hive数据仓库工具能将结构化的数据文件映射为一张数据库表,并提供SQL查询功能,能将SQL语句转变成MapReduce任务来执行。
Hive SQL 与 SQL 基本上一样,用法上的区别:
1、Hive 不支持事务,但是支持分区存储。
2、Hive 更适合于分析复杂的数据集,SQL更适合于快速分析不太复杂的数据集。
3、Hive不支持on子句中使用or,一般使用left join、right join或者join替代。
4、Hive不支持 ‘< dt <’这种格式的范围查找,可以用dt in(”,”)或者between替代。
5、Hive不支持增删改。
6、hive中没有not null,当字段为null时,使用\n代替。
7、SQL中null代表空值, 在Hive中String类型的字段若是空(empty)字符串, 即长度为0, 那么对它进行IS NULL的判断结果是False。
下面这个图,可能很多人就见过,是SQL的的表连接的语法总结,关于hive sql有相同的地方,也有不同的地方。



下面以mysql 50题的数据为例来讲。


join

内连接,返回两张表都有的数据。

    select s.*,sc.*
    from student s
    join score sc
    on s.student_id = sc.student_id

    结果:


    left join

    左连接,以左边的表为主表,返回的数据行数跟主表相同,关联不上的字段为NULL。

      select s.*,sc.*
      from student s
      left join score sc
      on s.student_id = sc.student_id

      结果:


      right join

      右连接,以右边的表为主表,返回的数据行数跟主表相同,关联不上的字段为NULL。

        select s.*,sc.*
        from student s
        right join score sc
        on s.student_id = sc.student_id

        结果同上面的join


        left out join

        同 left join,只是写法不一样


        right out join

        同 right join,只是写法不一样


        full out join

        全连接,返回两个表的并集,空缺的字段为NULL。

          select s.*,sc.*
          from student s
          full outer join score sc
          on s.student_id = sc.student_id

          结果同上面的right join


          left semi join

          并不拼接两张表,两个表对 on 的条件字段做交集,返回左表的记录,相较于其他的方法,这样子 hive 处理速度比较快。

            select s.*
            from student s
            left semi join score sc
            on s.student_id = sc.student_id


            map side join

            map side join使用场景是一个大表和一个小表的连接操作,其中,“小表”是指文件足够小,可以加载到内存中。该算法可以将join算子执行在Map端,无需经历shuffle和reduce等阶段,因此效率非常高。


            实际的一些题往往多表连查,例如mysql50题的第一题:
            查询"01"课程比"02"课程成绩高的学生的信息及课程分数:
              select s.*,sc.course_id,sc.score
              from student s
              join score sc
              on s.student_id = sc.student_id
              join
              (
              select sc1.student_id
              from (select * from score where course_id = 1) sc1
              join (select * from score where course_id = 2) sc2
              on sc1.student_id = sc2.student_id
              where sc1.score > sc2.score
              ) t
              on s.student_id = t.student_id;

              结果:

              总结:

              hive支持的连接包含join、left join、right join、left out join、right out join、full out join、left semi join、map side join等等,其实hive不支持笛卡尔积查询,但是join可以实现类似的操作。
              hive join 非常重要,是hive查询的基础知识,需要多加练习。




              文章转载自细说数据,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

              评论