【问题标题】:How to update Hive table rows如何更新 Hive 表行
【发布时间】:2020-11-30 20:52:48
【问题描述】:

我有一个如下所示的表格:

 id  | Col2 | Col3 | Text
--------------------------
  1  | ...  | ...  | "abc"   
  2  | ...  | ...  | "def 
  3  | ...  | ...  | "ghi"  
  4  | ...  | ...  | "jkl" 

还有一个看起来像这样的表:

 id  | Text
-------------
  1  | "qwe"
  2  | "rty"

我想最终得到一个如下所示的表格:

 id  | Col2 | Col3 | Text
--------------------------
  1  | ...  | ...  | "qwe"   
  2  | ...  | ...  | "rty" 
  3  | ...  | ...  | "ghi"  
  4  | ...  | ...  | "jkl" 

col2 和 col3 的原始值保持不变。本质上,我想使用表 2 中的值来更新 id 相同的表 1 的值。

我试过了:

SELECT
    A.id,
    col1, 
    col2, 
    A.text
FROM table1 AS A
LEFT JOIN (
    SELECT
        id,
        text
    FROM table2
) AS B
    ON A.product_id = B.product_id

但这只是返回了原始表。有没有办法在 Presto/Hive 中实现我想要的?

【问题讨论】:

    标签: hive presto


    【解决方案1】:

    您正在从表 A 加载文本,如果要更新表 B 中存在的值,则它应该来自表 BNVL(B.text, A.Text),如果不存在则保持原样(参见代码中的注释)

    INSERT OVERWRITE table1 
    SELECT
        A.id,
        col1, 
        col2, 
        NVL(B.text, A.Text) as Text  -- Take Text from table B, if not exists, leave as is (A.Text)
    FROM table1 AS A
    LEFT JOIN B ON A.product_id = B.product_id
    

    您可以使用coalesce(B.text, A.Text) 而不是NVL,正如@PiotrFindeisen 所提到的,它也可以在Presto 和Hive 上正常工作。

    【讨论】:

    • 您可能希望将coalesce 用于标准的便携式解决方案。
    • @PiotrFindeisen 是的,你是对的。 coalesce() 而不是 NVL() 在 Presto 和 Hive 上也可以正常工作
    • 我使用了 coalesce 并且效果很好!非常感谢,我以前不知道该功能存在:)
    猜你喜欢
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 2017-05-12
    • 2016-11-06
    • 2019-08-20
    • 1970-01-01
    相关资源
    最近更新 更多