Hive SQL常用语法总结

  Hive是一个数据仓库基础的应用工具,在Hadoop中用来处理结构化数据,通过类SQL语言对数据进行操作。Hive将sql语句通过解析器转换成MapReduce作业提交到Hadoop集群上,Hadoop监控作业执行过程,并将执行结果返回给用户。

  值得注意的是,Hive并支持行级数据的更新,主要使用场合为大数据集的批处理作业中。

  下面为Hive中常用的SQL语句,‘[ ]’中的内容根据实际需求来确定要不要写。

-- 创建数据库
create database name;

-- 常用显示命令
show databases; -- 查看有哪些数据库
show tables;  -- 查看当前数据库下有哪些表
show tables like '*cc*'  -- 正则表达式显示表
show partitions;  -- 查看分区
show functions;
describe extended table_name;    -- 查看表的结构,字段,分区等情况

-- 建表语句
create [external] table [if not exists] table_name   --创建表,指定表名,默认为内部表
[(col_name data_type [comment col_comment], ...)]  -- 创建字段,指定字段类型、注释
[comment table_comment]  -- 表的注释
[partitioned by (col_name data_type [comment col_comment], col_name_2 data_type_2, ...)] -- 指定分区,要注意分区字段不能出现的建表的字段中
[clustered by (col_name, col_name_2, ...)] [sorted by (col_name [ASC|DESC], ...)] into num_buckets buckets] -- 分桶
[row format row_format]
[stored as file_format]  -- 指定存储文件类型
[location hdfs_path]  -- 存储路径

·external 表示创建的表是否为外部表,默认为内部表
·if not exists 表示该表不存在时创建该表,否则忽略异常
·comment 为表、字段增加注释
·row_format
    row format delimited [fields terminated by char]
                         [collection items terminated by char]
                         [map keys terminated by char]
                         [lines terminated by char]
·file_format
   stored as textfile  -- 纯文本数据
   stored as sequencefile  -- 数据需要压缩,节省存储空间

-- like关键字复制表结构
create table table_name like old_table_name;         

-- 更改表名
alter table table_name rename to new_table_name;

-- 增加一个字段 并 添加注释
alter table table_name add columns (col_name data_type comment 'col_comment');

-- 删除列
alter table table_name replace columns (col_name data_type, col_name_2 data_type_2);

-- 增加、删除分区
alter table table_name add [if not exists] partition_name;  -- 增加
alter table table_name drop partition_name, partition_name_2;   -- 删除
-- 插入数据
insert into table_1 select * from table_2;  -- 在table_1后追加数据
insert overwrite table_1 select * from table_2;  -- 先将table_1中数据清空,然后添加数据

-- 提取数据常用语句
select [distinct] select_expr_1, select_expr_2
from table_name
[where condition]   -- 筛选条件
[group by col_list [having condition]]  -- 分组、分组返回的条件
[order by col_list]  -- 排序
[limit num_1, num_2]   -- 返回数据的起始位置(num_1)以及返回数据的记录数(num_2)

猜你喜欢

转载自www.cnblogs.com/beyondChan/p/11409134.html