CTAS建表語句(CREATE TABLE AS SELECT)
-
使用查詢創建並填充表,select中選取的列名會作爲新表的列名(所以通常是要取別名)
-
會改變表的屬性、結構,比如只能是內部表、分區分桶也沒了
- 目標表不允許使用分區分桶的,
FAILED: SemanticException [Error 10068]: CREATE-TABLE-AS-SELECT does not support partitioning in the target table
對於舊錶中的分區字段,如果通過select * 的方式,新表會把它看作一個新的字段,這裏要注意 - 目標表不允許使用外部表,如create external table … as select…報錯
FAILED: SemanticException [Error 10070]: CREATE-TABLE-AS-SELECT cannot create external table
- CTAS創建的表存儲格式會變成默認的格式TEXTFILE
- 對了,還有字段的註釋comment也會丟掉,同時新表也無法加上註釋
- 目標表不允許使用分區分桶的,
-
但可以在CTAS語句中指定表的存儲格式,行和列的分隔符等
create table xxx as select ...
create table xxx
row format delimited
fields terminated by ' '
stored as parquet
as
select ...
如何快速複製一張分區表?
create table... like...
+insert into table ... partition(xxx)...select...
- 或者通過hdfs複製數據並修復新表的分區相關元數據
create table newtable like oldtable
hdfs dfs -cp /old_table/ /path/new_table/
msck repair table newtable
第一種方法會慢很多,但涉及要對舊錶進行相關操作的話,也就只能用第一種動態分區的方法
create [external] table partition_test like old_table;
insert into table partition_test
partition(dt)
select
trim(userid) userid,
trim(cardno) cardno,
if(lower(trim(flag)) in ("true","1","01"),"1","0") flag,
substr(cardtype,1,1) cardtype,
trim(times) times,
substr(times,0,10) dt
from old_table
order by rand()
limit 100;
CREATE TABLE LIKE 語句
- 用來複製表的結構
- 需要外部表的話,通過create external table as …指定
- 不CTAS語句會填充數據
更多大數據相關Tips可以關注:https://github.com/josonle/Coding-Now 和 https://github.com/josonle/BigData-Learning