拉链表是针对hive中数据仓库设计中为表存储数据的方式而设计的,所谓拉链表。就是记录一个事物从开始,一直到当前状态的所有变化的信息,表中每个事物的每一个变化都清晰可见。
以此表为例
左侧his表就是拉链表,记载着表中每个id的变化记录;
而右侧的inc表为增量表,记载以day为分区的前一天的增量数据,为第二天数据查询提供数据支持。
注意两表联合查询时,
-- 两表查询 合并 UNIN ALL --
-- 通过his left join inc 找出订单状态有更新的数据 --
-- 将inc 2021-11-21的数据添加end_time为9999-12-31后插入his表 --
注意点: 1.以his表为主,以inc为辅 2.去除 null
3.当end_time>modifiedtime,把end_time时间改成modifiedtime时间
4.两表查询后,最后排一下序,按照id、start_time
然后, 两张表的联合查询语句如下,为了方便后面查询,我把查询结果放在了一个新表里
create table dws_his_20211122_tmp as
select t.orderid,t.createtime,t.modifiedtime,
t.status,t.start_time,t.end_time
from
(
select
t1.orderid,
t1.createtime,
t1.modifiedtime,
t1.status,
t1.start_time,
case when t2.orderid is not null and t1.end_time > '2021-11-22' then '2021-11-22' else t1.end_time end end_time
from dws_orders_his t1
left join
(select orderid from ods_orders_inc where day='2021-11-22') t2
on t1.orderid=t2.orderid
union all
select
orderid,
createtime,
modifiedtime,
status,
modifiedtime as start_time,
'9999-12-31' as end_time
from ods_orders_inc where day='2021-11-22'
) t
order by t.orderid,t.start_time
hive> select * from dws_his_20211122_tmp;
OK
1 2021-11-20 2021-11-20 创建 2021-11-20 2021-11-21
1 2021-11-20 2021-11-21 支付 2021-11-21 2021-11-22
1 2021-11-20 2021-11-22 完成 2021-11-22 9999-12-31
2 2021-11-20 2021-11-20 创建 2021-11-20 2021-11-21
2 2021-11-20 2021-11-21 支付 2021-11-21 9999-12-31
3 2021-11-20 2021-11-20 创建 2021-11-20 2021-11-22
3 2021-11-20 2021-11-22 支付 2021-11-22 9999-12-31
4 2021-11-21 2021-11-21 创建 2021-11-21 2021-11-22
4 2021-11-21 2021-11-22 支付 2021-11-22 9999-12-31
5 2021-11-22 2021-11-22 创建 2021-11-22 9999-12-31
最后,为了方便下一次的查询,我们把查出来的结果表dws_his_20211122_tmp的数据覆盖写入拉链表dws_orders_his,形成新的拉链表
hive> insert overwrite table dws_orders_his select * from dws_his_20211122_tmp;
hive> select * from dws_his_20211122_tmp;
OK
1 2021-11-20 2021-11-20 创建 2021-11-20 2021-11-21
1 2021-11-20 2021-11-21 支付 2021-11-21 2021-11-22
1 2021-11-20 2021-11-22 完成 2021-11-22 9999-12-31
2 2021-11-20 2021-11-20 创建 2021-11-20 2021-11-21
2 2021-11-20 2021-11-21 支付 2021-11-21 9999-12-31
3 2021-11-20 2021-11-20 创建 2021-11-20 2021-11-22
3 2021-11-20 2021-11-22 支付 2021-11-22 9999-12-31
4 2021-11-21 2021-11-21 创建 2021-11-21 2021-11-22
4 2021-11-21 2021-11-22 支付 2021-11-22 9999-12-31
5 2021-11-22 2021-11-22 创建 2021-11-22 9999-12-31
乐于奉献共享,帮助你我他!