區分insert into 和 insert overowrite:
0、
命令格式
INSERT OVERWRITE|INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)] [(col1,col2 ...)] select_statement FROM from_statement;
參數說明
- tablename:需要插入數據的目標表名稱。
- PARTITION (partcol1=val1, partcol2=val2 ...):需要插入數據的分區名稱,此參數不允許使用函數等表達式,只能是常量。
- select_statement:SELECT子句,從源表中查詢需要插入的數據。
- from_statement:FROM子句,代表數據來源。例如,源表名稱。
功能說明
INSERT OVERWRITE/INTO
用於將計算的結果保存目標表中。
- insert into:直接向表或表的分區中追加數據。
- insert overwrite:先清空表中的原有數據,再向表或分區中插入數據。
示例
- 計算
sale_detail
表中不同地區的銷售額存入表sale_detail_insert
中。--創建目標表sale_detail_insert。 create table sale_detail_insert like sale_detail; --給目標表增加分區。 alter table sale_detail_insert add partition(sale_date='2013', region='china'); --從源表sale_detail中取出數據插入目標表sale_detail_insert。 insert overwrite table sale_detail_insert partition (sale_date='2013', region='china') select shop_name, customer_id,total_price from sale_detail;
- 源表與目標表的對應關系依賴於在
select
子句中列的順序,而不是表與表之間列名的對應關系。例如如下語句。insert overwrite table sale_detail_insert partition (sale_date='2013', region='china') select customer_id, shop_name, total_price from sale_detail;
在創建
sale_detail_insert
表時,列的順序為shop_name string、customer_id string、total_price bigint
,而從sale_detail
向sale_detail_insert
插入數據的順序為customer_id、shop_name、total_price
。此時,會將sale_detail.customer_id
的數據插入sale_detail_insert.shop_name
,將sale_detail.shop_name
的數據插入sale_detail_insert.customer_id
。 - 向某個分區插入數據時,分區列不允許出現在
select
列表中。下面語句報錯返回,sale_date,region
為分區列,不允許出現在靜態分區的insert語句中。insert overwrite table sale_detail_insert partition (sale_date='2013', region='china') select shop_name, customer_id, total_price, sale_date, region from sale_detail;
partition
的值只能是常量,不可以出現表達式。以下為錯誤用法。insert overwrite table sale_detail_insert partition (sale_date=datepart('2016-09-18 01:10:00', 'yyyy') , region='china') select shop_name, customer_id, total_price from sale_detail;
使用動態分區注意事項
insert into partition
時,如果分區不存在,會自動創建分區。- 多個
insert into partition
作業並發時,如果分區不存在,會自動創建分區,但只會成功創建一個分區。 - 如果不能控制
insert into partition
作業並發,則只能通過預創建分區避免問題。
1、insert into 語句
Hive> insert into table account select id,age,name from account_tmp;
2、insert overwrite語句
hive> insert overwrite table account2 select id,age,name from account_tmp;
--------------------
overwrite本質是覆蓋現有數據!!!!(清空原有數據,新增查詢數據),而into是直接將數據寫入庫。
參考:
https://blog.csdn.net/paopaopotter/java/article/details/83616295
https://blog.csdn.net/qq_41582642/article/details/82897424