全量数据与增量数据同步
1、不关心主键:
a、第一次直接全量同步:
insert overwrite table target select * from source
b、第二次以后采用增量同步:表一般都有
createtime, updatetime
如:
insert into table target
select * from source where to_date(updatetime) >= date_add(CURRENT_DATE,-1) /(方式二)date_sub(to_date(CURRENT_TIMESTAMP),1)
2.关心主键:
a、研发落表,都有主键id,MySql
– 创建临时表,同步过来的数据加载到临时表:
load data local inpath ‘/tmp.txt’ overwrite into table tmp
–增量数据和目标数据合并
LEFT JOIN返回左表的全部行和右表满足ON条件的行,如果左表的行在右表中没有匹配,那么这一行右表中对应数据用NULL代替。
insert overwrite table target
--新增数据
select * from tmp
union all
--未新增的数据
select a.* from target a
left join tmp b
on a.id = b.id
-- a表中有的id而b表中没有的id
where b.id is null
删除临时表:
drop table if exists tmp;
b、比如用户针对一个订单发生多次改派,这里我们只关心终态
order_id updatetime rank
10001 2020-12-26 12:00:01 3
10001 2020-12-26 12:00:10 2
10001 2020-12-26 12:00:13 1
select *
from
(select *
,row_number() over (partition by order_id updatetime desc ) rank
from target
) t
where t.rank=1
Hive日期比较函数详解
to_date函数:
select to_date(‘2018-12-08 10:03:01’);–2018-12-08 返回日期时间字段中的日期部分
1.日期比较函数: datediff语法: datediff(string enddate,string startdate)
返回值: int
说明: 返回结束日期减去开始日期的天数。
举例:
hive> select datediff(‘2020-12-30’,‘2020-12-29’);
1
2.日期增加函数: date_add语法: date_add(string startdate, intdays)
返回值: string
说明: 返回开始日期startdate增加days天后的日期。
举例:
hive>select date_add(‘2020-12-29’,10);
2021-01-08
3.日期减少函数: date_sub语法: date_sub (string startdate,int days)
返回值: string
说明: 返回开始日期startdate减少days天后的日期。
举例:
hive>select date_sub(‘2020-12-29’,10);
2020-12-19
4.查询近30天的数据
select * from table where datediff(current_timestamp,create_time)<=30;
create_time 为table里的字段,current_timestamp 返回当前时间 2020-06-01 11:00:00