多表关联顺序的问题

当多张表进行关联的时候,既有 LEFT JOIN,又有 JOIN,此时的关联顺序是如何进行的,假设我们有三张表,数据如下:

① 用户信息表

-- 用户信息表
create table if not exists user_temp
(
    user_id string comment '用户ID',
    user_name string comment '用户姓名',
    emp_id string comment '部门ID'
)
comment '客户信息表'
partitioned by (ds string)
stored as orc tblproperties ('orc.compress'='SNAPPY')
;

在这里插入图片描述
② 公司部门表

-- 部门表
create table if not exists emp_temp
(
    emp_id string comment '部门ID',
    emp_name string comment '部门名称'
)
comment '部门信息表'
partitioned by (ds string)
stored as orc tblproperties ('orc.compress'='SNAPPY')
;

在这里插入图片描述

③ 用户订单表

-- 订单表
create table if not exists order_temp
(
    user_id string comment '用户ID',
    order_id string comment '订单ID',
    order_name string comment '订单名称'
)
comment '订单信息表'
partitioned by (ds string)
stored as orc tblproperties ('orc.compress'='SNAPPY')
;

在这里插入图片描述

多表关联的顺序

① 需求描述

展示当前 A、B、D 部门的用户的订单详情,需要包含的字段有:用户ID、用户姓名、部门号、部门名称、用的订单号、订单名称

② 需求分析(只讨论关联顺序,不需要对需求本身过多讨论)

先通过用户表和部门表关联,剔除不存在的部门,此时获取到的用户只有:ABD 部门用户

将上一步结果和订单表做关联,有订单的则关联到订单数据,没订单则关联到的数据为 NULL

SELECT  t1.user_id
       ,t1.user_name
       ,t2.emp_id
       ,t2.emp_name
       ,t3.order_id
       ,t3.order_name
FROM
(
    SELECT  user_id
           ,user_name
           ,emp_id
    FROM user_temp
    WHERE ds = '20220222' 
) t1
JOIN
(
    SELECT  emp_id
           ,emp_name
    FROM emp_temp
    WHERE ds = '20220222' 
) t2
ON t1.emp_id = t2.emp_id
LEFT JOIN
(
    SELECT  user_id
           ,order_id
           ,order_name
    FROM order_temp
    WHERE ds = '20220222' 
) t3
ON t1.user_id = t3.user_id 
;

在这里插入图片描述
③ 多表关联的顺序的结论

HIVE 的关联书序从上到下依次执行,例如三张表 t1、t2、t3 依次关联,则按照关联顺序依次执行

HIVE 会对每个 JOIN 连接对象启动一个 MapReduce 任务,上面的列子首先会启动一个MapReduce 任务对表 t1 和表 t2 进行连接操作,然后会再启动一个 MapReduce 任务将第一个 MapReduce 任务的输出和表 t3 进行连接操作

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐