天天看點

hive-内部表與外部表的差別

本文以例子的形式介紹一下Hive内表和外表的差別。例子共有4個:不帶分區的内表、帶分區的内表、不帶分區的外表、帶分區的外表。

1 不帶分區的内表

#建立表

create table innerTable(id int,name string) row format delimited fields terminated by '|';(show tables發現沒有innerTable,隻有innertable。不多說,記住了)

#從HDFS上加載資料

load data inpath 'hdfs://master:9000/user/root/test/innerTable' into table innertable; (檢視HDFS上/user/root/test/innerTable,發現檔案價innerTable還在,但是裡面的檔案已經不在了。去哪了,去innertable表中了)

#删除剛剛建立的表

drop table innertable;(到HDFS上看一下innertable檔案夾及其中的檔案都沒有了。去哪了,删除表的時候删除了)

2 帶分區的内表

#建立表

create table inner_table_with_p(id int,name string) partitioned by (part_num int);(HDFS 出現檔案夾inner_table_with_p,檔案夾中為空)

#從HDFS加載資料

load data inpath 'hdfs://master:9000/user/root/test/innerTable/part1' into table inner_table_with_p partition(part_num=1)(檔案夾inner_table_with_p出現子檔案夾part_num=1,innerTable中part1消失);

load data inpath 'hdfs://master:9000/user/root/test/innerTable/part2' into table inner_table_with_p partition(part_num=2)(檔案夾inner_table_with_p出現子檔案夾part_num=2,innerTable中part2消失);

load data inpath 'hdfs://master:9000/user/root/test/innerTable/part3' into table inner_table_with_p partition(part_num=3)(檔案夾inner_table_with_p出現子檔案夾part_num=3,innerTable中part3消失);

#删除分區

alter table inner_table_with_p drop partition(part_num=1);(part_num=1對應分區檔案夾本删除)

#删除表

drop table inner_table_with_p;(HDFS上inner_table_with_p檔案夾被删除)

3 不帶分區的外表

建立表

create external table outer_table(id int,name string) row format delimited fields terminated by '|';      (hive倉儲目錄中出現outer_table)

加載資料

load data inpath '/user/root/test/outerTable/outer' into table outer_table;(outer_table中出現子檔案outer,outerTable中outer消失)

删除表

drop table outer_table;    (outer_table及子檔案outer依然存在,因為這是外表)

4 帶分區的外表

建立表

create external table outer_table_with_p(id int,name string) partitioned by (part_num int) row format delimited fields terminated by '|'; (hive倉儲目錄中出現outer_table_with_p)

加載資料

load data inpath '/user/root/test/outerTable/part1' into table outer_table_with_p partiton(part_num=1);  (outer_table_with_p中出現子檔案夾part_num=1)

load data inpath '/user/root/test/outerTable/part2' into table outer_table_with_p partition(part_num=2);(outer_table_with_p中出現子檔案夾part_num=2)

load data inpath '/user/root/test/outerTable/part3' into table outer_table_with_p partition(part_num=3);(outer_table_with_p中出現子檔案夾part_num=3)

删除分區

alter table outer_table_with_p drop partition(part_num=1);(HDFS上分區檔案依舊存在)

删除表

drop table outer_table_with_p;(HDFS上對應資料依舊存在)

總結:

1 删除内表時,内表資料會一并删除;

2 删除外表時,外表資料依舊存在。

繼續閱讀