如何在Hive SQL中构造临时表用于和其它的表做关联?


=Start=

缘由:

虽然现在大模型的能力真的很强了,绝大部分问题只要你描述的够清楚大模型都能够快速的给你解决方法/方案。但是为了让博客不至于继续荒芜下去,还是得时不时的记录一些内容,方便自己参考和回顾。

正文:

参考解答:

问题:对于50个左右的uid和email的映射关系信息,如何在hive SQL中构造临时表用于和其它的表做关联?

这种规模下,不需要单独落表,通常推荐两种写法:

如果只是一次性分析,优先推荐 stack。

写法一:stack

-- 报错版本
with uid_email_map as (
    select stack(
        3,
        '10001', '[email protected]',
        '10002', '[email protected]',
        '10003', '[email protected]'
    ) as (uid, email)
)
select  m.email
-- ,t.*
from    uid_email_map m
-- join    some_db.some_table t
-- on      m.uid = t.uid;

报错信息:
Sql 1: From line 2, column 12 to line 7, column 5: TABLE Function ‘stack’ should not use in select list directly, please use lateral view instead

改进方法:

with uid_email_map as (
    select  s.uid,
            s.email
    from    (select 1) tmp
    lateral view stack(
        3,
        '10001', '[email protected]',
        '10002', '[email protected]',
        '10003', '[email protected]'
    ) s as uid, email
)

select  m.email
-- ,t.*
from    uid_email_map m
-- join    some_db.some_table t
-- on      m.uid = t.uid;

写法二:union all

with uid_email_map as (
              select 10001 as uid, '[email protected]' as email
    union all select 10002 as uid, '[email protected]' as email
    union all select 10003 as uid, '[email protected]' as email
)
select  m.uid
        ,m.email
        -- ,t.*
from    uid_email_map m
-- join    target_table t
-- on      m.uid = t.uid;

扩展信息

在Hive SQL中,如何快速的将一批数字ID和其它的数据表进行关联?

你现在的写法可以用,但当 ID 数量较多时,不建议把所有 ID 拼成一个长字符串再 split + explode。更推荐按场景选择以下几种方式:

场景推荐方式说明
几个到几十个 IDIN (…)最简单,适合临时查询
几十到几千个 IDstack / union all 构造临时表可读性和类型控制更好
几千到几十万 ID上传成临时表 / 分区表后 join最稳定、最适合生产或重复使用
ID 来自文件建外部表或临时落表避免 SQL 过长、解析慢
ID 集合需要频繁复用维护一张维表 / 白名单表最规范,便于权限、审计和复用
参考链接:

通义千问
https://www.qianwen.com/

=END=


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注