【问题标题】:Join two tables based on different column type根据不同的列类型连接两个表
【发布时间】:2019-12-18 06:02:58
【问题描述】:

我有两个具有以下架构的表作为示例:

   scala> df1.printSchema
   root
    |-- id: string (nullable = true)

   AND

   scala> df2.printSchema
   root
    |-- col1: string (nullable = true)
    |-- col2: array (nullable = true)
    |    |-- element: string (containsNull = true)

我想获取 df2 中的所有 col1,其中 col2 数组中的元素等于 df1 中的 id。输出诸如 df3 之类的东西:

   scala> df3.printSchema
   root
    |-- c1: array (nullable = true)
    |    |-- element: string (containsNull = true)
    |-- c2: string (nullable = true)

其中 df3.c2 基本上是 df1.id 而 df3.c1 是满足上述相等性的所有 df2.col1 的数组。

任何 SQL (hive) 或 Scala 解决方案都非常有用。

【问题讨论】:

    标签: sql scala dataframe join hive


    【解决方案1】:

    在蜂巢中:

    select collect_set(df2.col1) as col1, df1.id as col2
     from df1
    inner join 
    (
    select --explode col2 array 
          col1, s.c2 as col2 
     from df2 lateral view explode(col2) s as c2 
    ) df2 on df1.id = df2.col2
    group by df1.id;
    

    【讨论】:

    • 当我向这个查询添加一个分区时,如下所示:“从 df2 横向视图爆炸(col2)s as c2”=>“从 df2 where partition='blah-blah'横向视图爆炸(col2 ) s as c2" 我收到以下错误:FAILED: ParseException line 8:90 missing ) at 'as' near 'c2'... 有什么想法吗?
    • @user3520791 将 where 放在横向视图之后。侧视图 explode(col2) s as c2 where partition='blah-blah'
    • ***** 工作!***** 谢谢
    【解决方案2】:

    我认为您不需要子查询:

    select collect_set(df2.col1) as col1, df1.id as col2
    from df2 lateral view
         explode(col2) s as c2 join
         df1
         on df1.id = s.c2
    group by df1.id;
    

    【讨论】:

    • 由于以下错误而失败:FAILED: SemanticException [错误 10085]: Line 3:5 JOIN with a LATERAL VIEW is not supported 'c2'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 2021-01-14
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多