Hive学习之HQL(DDL、DML、DQL)

目录

一、 DDL数据定义

1.1 创建数据库

1.2 查询数据库

1.2.1 显示数据库

1.2.2 查看数据库详情

1.2.3 切换当前数据库

1.3 删除数据库

1.4 创建表

1.4.1 内部表(管理表)

1.4.2 外部表

1.5 分区表

1.6 修改表

1.6.1 重命名表

1.6.2 增加/修改列信息

1.7 删除表

二、 DML数据操作

2.1 数据导入

2.1.1 向表中装载数据(Load)

2.1.2 通过查询语句向表中插入数据(Insert)

2.1.3 查询语句中创建表并加载数据(As Select)

2.1.4 创建表时通过location指定加载数据路径

2.2 数据导出

2.2.1 Insert导出

2.2.2 Hadoop命令导出到本地

2.2.3 Hive Shell 命令导出到本地

2.3 清除表中数据(Truncate)

三、DQL数据查询语言

3.1 基本查询

3.1.1 全表和特定列查询

3.1.2 列别名

3.1.3算数运算符

3.1.4 常用函数

3.2 where条件

3.2.1 比较运算符

3.2.2 Like和Rlike

3.2.3 逻辑运算符

3.3 分组

3.3.1 GroupBy语句

3.3.2 Having语句

3.4 Join语句

3.4.1 等值join

3.4.2 表的别名

3.4.3 内连接

3.4.4 左外连接

3.4.5 右外连接

3.4.6 全外连接

3.4.7 多表连接

3.4.8 笛卡尔积

3.4.9 连接谓词中不支持or

3.5 排序

3.5.1 全局排序(Order By)

3.5.2 按照别名排序

3.5.3 多个列排序

3.5.4 每个MapReduce内部排序(Sort By)

3.5.5 分区排序(Distribute By)

3.5.6 Cluster By

3.6 分桶及抽样查询

3.6.1 分桶表数据存储

3.6.2 分桶抽样查询

3.7 其他常用查询函数

3.7.1 空字段赋值

3.7.3 行转列

3.7.4 列转行

四、函数

4.1 系统内置函数

4.2 自定义函数

4.3 自定义UDF函数


DDL:   database definition language 数据定义语言  引起的是结构上变化,不会影响数据 create drop alter

DML:  DataManipulationLanguage 数据操作语言  不会引起结构上的变化 引起的是数据的变化 update

DQL: 数据查询语言 不会引起结构上的变化,也不会引起数据的变化,select where


一、 DDL数据定义

1.1 创建数据库

1)创建一个数据库,数据库在HDFS上的默认存储路径是/user/hive/warehouse/*.db。

hive (default)> create database db_hive;

2)避免要创建的数据库已经存在错误,增加if not exists判断。(标准写法)

hive (default)> create database db_hive;
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Database db_hive already exists
hive (default)> create database if not exists db_hive;

3)创建一个数据库,指定数据库在HDFS上存放的位置

hive (default)> create database db_hive2 location '/db_hive2.db';

1.2 查询数据库

1.2.1 显示数据库

1)显示数据库

hive> show databases;

2)过滤显示查询的数据库

hive> show databases like 'db_hive*';
OK
db_hive
db_hive_1

1.2.2 查看数据库详情

1)显示数据库信息

hive> desc database db_hive;
OK
db_hive hdfs://hadoop003:9000/user/hive/warehouse/db_hive.db bigdataUSER

1.2.3 切换当前数据库

hive (default)> use db_hive;

1.3 删除数据库

1.删除空数据库

hive>drop database db_hive2;

2.如果删除的数据库不存在,最好采用 if exists判断数据库是否存在

hive> drop database db_hive;
FAILED: SemanticException [Error 10072]: Database does not exist: db_hive
hive> drop database if exists db_hive2;

3.如果数据库不为空,可以采用cascade命令,强制删除

hive> drop database db_hive;
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. InvalidOperationException(message:Database db_hive is not empty. One or more tables exist.)
hive> drop database db_hive cascade;

1.4 创建表

        内部表与外部表的区别在于删除时候不同,如果删除的是内部表,那么会把元数据、hdfs的业务数据全部删除。如果删除的是外部表,那么只会把元数据删除,而保留hdfs的业务数据。

创建表的时候,怎么选择创建内部表还是外部表呢?

(1)hdfs业务数据的所属上,如果某hdfs业务数据属于自己,则可以创建内部表,

(2)hdfs业务数据是否要共享,如果在创建好表之后,表要共享,尽量要创建外部表,防止他们将表删除之后,hdfs也随之被删除。

1建表语法

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], ...)]
[CLUSTERED BY (col_name, col_name, ...)
[SORTED BY (col_name [ASC|DESC], ...)] INTO num_buckets BUCKETS]
[ROW FORMAT row_format]
[STORED AS file_format]
[LOCATION hdfs_path]
like

2字段解释说明

(1)CREATE TABLE 创建一个指定名字的表。如果相同名字的表已经存在,则抛出异常;用户可以用 IF NOT EXISTS 选项来忽略这个异常。

(2)EXTERNAL关键字可以让用户创建一个外部表,在建表的同时指定一个指向实际数据的路径(LOCATION),Hive创建内部表时,会将数据移动到数据仓库指向的路径;若创建外部表,仅记录数据所在的路径,不对数据的位置做任何改变。在删除表的时候,内部表的元数据和数据会被一起删除,而外部表只删除元数据,不删除数据。

(3)COMMENT:为表和列添加注释。

(4)PARTITIONED BY:创建分区表

(5)CLUSTERED BY:创建分桶表

(6)SORTED BY:不常用

(7)ROW FORMAT

         DELIMITED [FIELDS TERMINATED BY char] [COLLECTION ITEMS TERMINATED BY char]

         [MAP KEYS TERMINATED BY char] [LINES TERMINATED BY char]

         | SERDE serde_name [WITH SERDEPROPERTIES (property_name=property_value, property_name=property_value, ...)]

        用户在建表的时候可以自定义SerDe或者使用自带的SerDe。如果没有指定ROW FORMAT 或者ROW FORMAT DELIMITED,将会使用自带的SerDe。在建表的时候,用户还需要为表指定列,用户在指定表的列的同时也会指定自定义的SerDe,Hive通过SerDe确定表的具体的列的数据。

        SerDe是Serialize/Deserilize的简称,目的是用于序列化和反序列化。

(8)STORED AS指定存储文件类型

        常用的存储文件类型:SEQUENCEFILE(二进制序列文件)、TEXTFILE(文本)、RCFILE(列式存储格式文件)

        如果文件数据是纯文本,可以使用STORED AS TEXTFILE。如果数据需要压缩,使用 STORED AS SEQUENCEFILE。

(9)LOCATION :指定表在HDFS上的存储位置。

(10)LIKE允许用户复制现有的表结构,但是不复制数据。

1.4.1 内部表(管理表)

 1.理论 

        默认创建的表都是所谓的管理表,有时也被称为内部表。因为这种表,Hive会(或多或少地)控制着数据的生命周期。Hive默认情况下会将这些表的数据存储在由配置项hive.metastore.warehouse.dir(例如,/user/hive/warehouse)所定义的目录的子目录下。当我们删除一个内部表时,Hive也会删除这个表中数据(元数据和表数据都会删除掉)。管理表不适合和其他工具共享数据。

 2.案例实操 

(1)普通创建表

create table if not exists student3(
id int, name string
)
row format delimited fields terminated by '\t'
stored as textfile
location '/user/hive/warehouse/student3';

(2)根据查询结果创建表(查询的结果会添加到新创建的表中)

create table if not exists student3 as select id, name from student;

3)根据已经存在的表结构创建表

create table if not exists student4 like student;

(4)查询表的类型

hive (default)> desc formatted student2;
Table Type:             MANAGED_TABLE  

1.4.2 外部表

 1.理论 

        因为表是外部表,所Hive并非认为其完全拥有这份数据。删除该表并不会删除掉这份数据,不过描述表的元数据信息会被删除掉。

 2.管理表和外部表的使用场景 

        每天将收集到的网站日志定期流入HDFS文本文件。在外部表(原始日志表)的基础上做大量的统计分析,用到的中间表、结果表使用内部表存储,数据通过SELECT+INSERT进入内部表。

 3.案例实操 

分别创建部门和员工外部表,并向表中导入数据。

(1)原始数据

dept.txt

emp.txt

(2)建表语句

创建部门表

create external table if not exists dept(
deptno int,
dname string,
loc int
)
row format delimited fields terminated by '\t';

创建员工表

create external table if not exists emp(
empno int,
ename string,
job string,
mgr int,
hiredate string,
sal double,
comm double,
deptno int)
row format delimited fields terminated by '\t';

(3)查看创建的表

hive (default)> show tables;
OK
tab_name
dept
emp

(4)向外部表中导入数据

导入数据

hive (default)> load data local inpath '/opt/module/datas/dept.txt' into table default.dept;

hive (default)> load data local inpath '/opt/module/datas/emp.txt' into table default.emp;

查询结果

hive (default)> select * from emp;

hive (default)> select * from dept;

(5)查看表格式化数据

hive (default)> desc formatted dept;

Table Type:             EXTERNAL_TABLE

1.5 分区

        分区表实际上就是对应一个HDFS文件系统上的独立的文件夹,该文件夹下是该分区所有的数据文件。Hive中的分区就是分目录,把一个大的数据集根据业务需要分割成小的数据集。在查询时通过WHERE子句中的表达式选择查询所需要的指定的分区,这样的查询效率会提高很多。减小搜索范围

1 分区表基本操作

1.引入分区表(需要根据日期对日志进行管理)

/user/hive/warehouse/log_partition/20180702/20180702.log

/user/hive/warehouse/log_partition/20180703/20180703.log

/user/hive/warehouse/log_partition/20180704/20180704.log

2.创建分区表语法

hive (default)> create table dept_partition(
deptno int, dname string, loc string
)
partitioned by (month string)
row format delimited fields terminated by '\t';

3.加载数据到分区表中

hive (default)> load data local inpath '/opt/module/datas/dept.txt' into table default.dept_partition partition(month='201809');

hive (default)> load data local inpath '/opt/module/datas/dept.txt' into table default.dept_partition partition(month='201808');

hive (default)> load data local inpath '/opt/module/datas/dept.txt' into table default.dept_partition partition(month='201807');

4.查询分区表中数据

单分区查询

hive (default)> select * from dept_partition where month='201809';

多分区联合查询

hive (default)> select * from dept_partition where month='201809'
              union
              select * from dept_partition where month='201808'
              union
              select * from dept_partition where month='201807';

创建单个分区

hive (default)> alter table dept_partition add partition(month='201806') ;

同时创建多个分区用空格分开

hive (default)> alter table dept_partition add partition(month='201805') partition(month='201804');

6.删除分区

删除单个分区

hive (default)> alter table dept_partition drop partition (month='201804');

同时删除多个分区用逗号分开

hive (default)> alter table dept_partition drop partition (month='201805'), partition (month='201806');

7.查看分区表有多少分区

hive> show partitions dept_partition;

8.查看分区表结构

hive> desc formatted dept_partition;

2 分区表注意事项

1.创建二级分区表

hive (default)> create table dept_partition2(
               deptno int, dname string, loc string
               )
               partitioned by (month string, day string)
               row format delimited fields terminated by '\t';

2.正常的加载数据

(1)加载数据到二级分区表中

hive (default)> load data local inpath '/opt/module/datas/dept.txt' into table
 default.dept_partition2 partition(month='201809', day='13');

(2)查询分区数据

hive (default)> select * from dept_partition2 where month='201809' and day='13';

3.把数据直接上传到分区目录上,让分区表和数据产生关联的三种方式

(1)方式一:上传数据后修复

上传数据

hive (default)> dfs -mkdir -p
 /user/hive/warehouse/dept_partition2/month=201809/day=12;
hive (default)> dfs -put /opt/module/datas/dept.txt  /user/hive/warehouse/dept_partition2/month=201809/day=12;

查询数据(查询不到刚上传的数据)

hive (default)> select * from dept_partition2 where month='201809' and day='12';

执行修复命令

hive> msck repair table dept_partition2;

再次查询数据

hive (default)> select * from dept_partition2 where month='201809' and day='12';

(2)方式二:上传数据后添加分区

上传数据

hive (default)> dfs -mkdir -p
 /user/hive/warehouse/dept_partition2/month=201809/day=11;
hive (default)> dfs -put /opt/module/datas/dept.txt  /user/hive/warehouse/dept_partition2/month=201809/day=11;

执行添加分区

hive (default)> alter table dept_partition2 add partition(month='201809', day='11');

查询数据

hive (default)> select * from dept_partition2 where month='201809' and day='11';

(3)方式三:上传数据后load数据到分区

创建目录

hive (default)> dfs -mkdir -p

 /user/hive/warehouse/dept_partition2/month=201809/day=10;

上传数据

hive (default)> load data local inpath '/opt/module/datas/dept.txt' into table dept_partition2 partition(month='201809',day='10');

查询数据

hive (default)> select * from dept_partition2 where month='201809' and day='10';

1.6 修改表

1.6.1 重命名表

1.语法

ALTER TABLE table_name RENAME TO new_table_name

2.实操案例

hive (default)> alter table dept_partition2 rename to dept_partition3;

1.6.2 增加/修改列信息

1.语法

更新列

ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment]

增加列

ALTER TABLE table_name ADD COLUMNS (col_name data_type [COMMENT col_comment], ...)

注:ADD是代表新增一字段,字段位置在所有列后面

2.实操案例

(1)查询表结构

hive> desc dept_partition;

(2)添加列

hive (default)> alter table dept_partition add columns(deptdesc string);

(3)查询表结构

hive> desc dept_partition;

(4)更新列

hive (default)> alter table dept_partition change column deptdesc desc int;

(5)查询表结构

hive> desc dept_partition;

1.7 删除表

hive (default)> drop table dept_partition;

二、 DML数据操作

2.1 数据导入

2.1.1 向表中装载数据(Load)

1语法

hive> load data [local] inpath '/opt/module/datas/student.txt' [overwrite] into table student

(1)load data:表示加载数据

(2)local:表示从本地加载数据到hive表(复制);否则从HDFS加载数据到hive表(移动)

(3)inpath:表示加载数据的路径

(4)overwrite into:表示覆盖表中已有数据,否则表示追加

(5)into table:表示加载到哪张表

(6)student:表示具体的表

2实操案例

(0)创建一张表

hive (default)> create table student(id string, name string) row format delimited fields terminated by '\t';

(1)加载本地文件到hive  拷贝数据到hive表的位置

hive (default)> load data local inpath '/opt/module/datas/student.txt' into table default.student;

(2)加载HDFS文件到hive中

上传文件到HDFS

hive (default)> dfs -put /opt/module/datas/student.txt /user/root/hive;

加载HDFS上数据  移动数据到hive表的位置

hive (default)> load data inpath '/user/root/hive/student.txt' into table default.student;

(3)加载数据覆盖表中已有的数据

上传文件到HDFS

hive (default)> dfs -put /opt/module/datas/student.txt /user/root/hive;

加载数据覆盖表中已有的数据

hive (default)> load data inpath '/user/root/hive/student.txt' overwrite into table default.student;

2.1.2 通过查询语句向表中插入数据(Insert)

1.创建一张表

hive (default)> create table student(id int, name string) row format delimited fields terminated by '\t';

2.基本插入数据

hive (default)> insert into table  student values(1,'wangwang');

2.1.3 查询语句中创建表并加载数据(As Select)

根据查询结果创建表(查询的结果会添加到新创建的表中)

create table if not exists student3
as select id, name from student;

2.1.4 创建表时通过location指定加载数据路径

1.创建表,并指定在hdfs上的位置

hive (default)> create table if not exists student4(
              id int, name string
              )
              row format delimited fields terminated by '\t'
              location '/user/hive/warehouse/student4';

2.上传数据到hdfs上

hive (default)> dfs -put /opt/module/datas/student.txt
/user/hive/warehouse/student4;

3.查询数据

hive (default)> select * from student4;

2.2 数据导出

2.2.1 Insert导出

1.将查询的结果导出到本地

hive (default)> insert overwrite local directory '/opt/module/datas/export/student' select * from student;

2.将查询的结果格式化导出到本地

hive(default)>insert overwrite local directory '/opt/module/datas/export/student1' ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' select * from student;

3.将查询的结果导出到HDFS上(没有local)

hive (default)> insert overwrite directory '/user/bigdata/student2'
             ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
             select * from student;

2.2.2 Hadoop命令导出到本地

hive (default)> dfs -get /user/hive/warehouse/student/month=201809/student.txt

/opt/module/datas/export/student3.txt;

2.2.3 Hive Shell 命令导出到本地

基本语法:(hive -f/-e 执行语句或者脚本 > file)

[hadoop@hadoop003 hive]$ bin/hive -e 'select * from default.student;' >
 /opt/module/datas/export/student4.txt;

2.3 清除表中数据(Truncate)

注意:Truncate只能删除管理表,不能删除外部表中数据

hive (default)> truncate table student;

三、DQL数据查询语言

DQL查询语句语法:

SELECT [ALL | DISTINCT] select_expr, select_expr, ...
  FROM table_reference
  [WHERE where_condition]
  [GROUP BY col_list]
  [ORDER BY col_list]
  [CLUSTER BY col_list
    | [DISTRIBUTE BY col_list] [SORT BY col_list]
  ]
 [LIMIT number]

3.1 基本查询

分别创建部门和员工表,并向表中导入数据。

(1)原始数据

dept.txt

emp.txt

(2)建表语句

创建部门表

create table if not exists dept(
deptno int,
dname string,
loc int
)
row format delimited fields terminated by '\t';

创建员工表

create table if not exists emp(
empno int,
ename string,
job string,
mgr int,
hiredate string,
sal double,
comm double,
deptno int)
row format delimited fields terminated by '\t';

(3)查看创建的表

hive (default)> show tables;
OK
tab_name
dept
emp

(4)向外部表中导入数据

导入数据

hive (default)> load data local inpath '/opt/module/datas/dept.txt' into table default.dept;

hive (default)> load data local inpath '/opt/module/datas/emp.txt' into table default.emp;

3.1.1 全表和特定列查询

1.全表查询

hive (default)> select * from emp;

2.选择特定列查询

hive (default)> select empno, ename from emp;

注意:

(1)SQL 语言大小写不敏感

(2)SQL 可以写在一行或者多行

(3)关键字不能被缩写也不能分行

(4)各子句一般要分行写

(5)使用缩进提高语句的可读性

3.1.2 列别名

1.重命名一个列

2.便于计算

3.紧跟列名,也可以在列名和别名之间加入关键字‘AS’  对于中文别名,要加上反单引号。

4.案例实操

查询名称和部门

hive (default)> select ename AS name, deptno dn from emp;

3.1.3算数运算符

运算符

描述

A+B

A和B 相加

A-B

A减去B

A*B

A和B 相乘

A/B

A除以B

A%B

A对B取余

A&B

A和B按位取与

A|B

A和B按位取或

A^B

A和B按位取异或

~A

A按位取反

案例实操

查询出所有员工的薪水后加1显示。

hive (default)> select sal +1 from emp;

3.1.4 常用函数

1. 求总行数(count)

select count(*) from emp;

2. 求工资的最大值(max)

select max(sal) from emp;

3. 求工资的最小值(min)

select min(sal) from emp;

4. 求工资的总和(sum)

select sum(sal) from emp;

5. 求工资的平均值(avg)

select avg(sal) from emp;

3.1.5 limit语句

典型的查询会返回多行数据。LIMIT子句用于限制返回的行数。

hive (default)> select * from emp limit 5;

3.2 where条件

1.使用WHERE子句,将不满足条件的行过滤掉

2.WHERE子句紧随FROM子句

3.案例实操

查询出薪水大于1000的所有员工

select * from emp where sal > 1000;

3.2.1 比较运算符

1)下面表中描述了谓词操作符,这些操作符同样可以用于JOIN…ON和HAVING语句中。

 比较运算符见下表

操作符

支持的数据类型

描述

A=B

基本数据类型

如果A等于B则返回TRUE,反之返回FALSE

A<=>B

基本数据类型

如果A和B都为NULL,则返回TRUE,其他的和等号(=)操作符的结果一致,如果任一为NULL则结果为NULL

A<>B, A!=B

基本数据类型

A或者B为NULL则返回NULL;如果A不等于B,则返回TRUE,反之返回FALSE

A<B

基本数据类型

A或者B为NULL,则返回NULL;如果A小于B,则返回TRUE,反之返回FALSE

A<=B

基本数据类型

A或者B为NULL,则返回NULL;如果A小于等于B,则返回TRUE,反之返回FALSE

A>B

基本数据类型

A或者B为NULL,则返回NULL;如果A大于B,则返回TRUE,反之返回FALSE

A>=B

基本数据类型

A或者B为NULL,则返回NULL;如果A大于等于B,则返回TRUE,反之返回FALSE

A [NOT] BETWEEN B AND C

基本数据类型

如果A,B或者C任一为NULL,则结果为NULL。如果A的值大于等于B而且小于或等于C,则结果为TRUE,反之为FALSE。如果使用NOT关键字则可达到相反的效果。

A IS NULL

所有数据类型

如果A等于NULL,则返回TRUE,反之返回FALSE

A IS NOT NULL

所有数据类型

如果A不等于NULL,则返回TRUE,反之返回FALSE

IN(数值1, 数值2)

所有数据类型

使用 IN运算显示列表中的值

A [NOT] LIKE B

STRING 类型

B是一个SQL下的简单正则表达式,如果A与其匹配的话,则返回TRUE;反之返回FALSE。B的表达式说明如下:‘x%’表示A必须以字母‘x’开头,‘%x’表示A必须以字母’x’结尾,而‘%x%’表示A包含有字母’x’,可以位于开头,结尾或者字符串中间。如果使用NOT关键字则可达到相反的效果。

A RLIKE B, A REGEXP B

STRING 类型

B是一个正则表达式,如果A与其匹配,则返回TRUE;反之返回FALSE。匹配使用的是JDK中的正则表达式接口实现的,因为正则也依据其中的规则。例如,正则表达式必须和整个字符串A相匹配,而不是只需与其字符串匹配。

2)案例实操

(1)查询出薪水等于5000的所有员工

select * from emp where sal = 5000;

(2)查询工资在500到1000的员工信息

select  * from emp where sal between 500 and 1000;

(3)查询comm为空的所有员工信息

select * from emp where comm is null;

(4)查询工资是1500或者5000的员工信息

select * from emp where sal = 1500 or sal = 5000;

select * from emp where sal in (1500,5000);

3.2.2 Like和Rlike

1)使用LIKE运算选择类似的值

2)选择条件可以包含字符或数字:

% 代表零个或多个字符(任意个字符)。

_ 代表一个字符。

3)RLIKE子句是Hive中这个功能的一个扩展,其可以通过Java的正则表达式这个更强大的语言来指定匹配条件。

4)案例实操

(1)查找以2开头薪水的员工信息

select * from emp where sal like '2%';

(2)查找第二个数值为2的薪水的员工信息

select * from emp where sal like '_2%';

(3)查找薪水中含有2的员工信息

select * from emp where sal like '%2%';

select * from emp where sal rlike '[2]';

3.2.3 逻辑运算符

操作符

含义

AND

逻辑并

OR

逻辑或

NOT

逻辑否

案例实操

(1)查询薪水大于1000,部门是30

select * from emp where sal > 1000 and deptno = 30;

(2)查询薪水大于1000,或者部门是30

select * from emp where sal > 1000 or deptno = 30;

(3)查询除了20部门和30部门以外的员工信息

select * from emp where deptno not in (20,30)

3.3 分组

3.3.1 GroupBy语句

GROUP BY语句通常会和聚合函数一起使用,按照一个或者多个列对结果进行分组,然后对每个组执行聚合操作。

案例实操:

(1)计算emp表每个部门的平均工资

select deptno, avg(sal)  from emp group by deptno;

(2)计算emp每个部门中每个岗位的最高薪水

select deptno,job, max(sal)  from emp group by deptno,job;

3.3.2 Having语句

1.having与where不同点

(1)where针对表中的列发挥作用,查询数据;having针对查询结果中的列发挥作用,筛选数据。

(2)where后面不能写分组函数,而having后面可以使用分组函数。

(3)having只用于group by分组统计语句。

2.案例实操

(1)求每个部门的平均薪水大于2000的部门

having 用于对结果中的列进行过滤

求每个部门的平均工资;

select deptno,avg(sal) from emp group by deptno;

求每个部门的平均薪水大于2000的部门:

select deptno,avg(sal) from emp group by deptno having avg(sal) > 2000;

 

3.4 Join语句

join是发生在 多个表之间, 内连接(等值内连接和不等值内连接)和外连接 (左外连接、右外连接,全外连接)

内连接:只会显示满足条件的数据。

外连接:会全部显示出某表的数据,如果另外一张表 跟它无法匹配,则另外一张表的相关字段设置为空。

3.4.1 等值join

Hive支持通常的SQL JOIN语句,但是只支持等值连接,不支持非等值连接。

案例实操

  1. 根据员工表和部门表中的部门编号相等,查询员工编号、员工名称和部门名称;
select e.empno,e.ename,d.dname from emp e,dept d where e.deptno=d.deptno;

select e.empno,e.ename,d.dname from emp e join dept d on e.deptno=d.deptno;

select e.empno,e.ename,d.dname from emp e inner join dept d on e.deptno=d.deptno;

3.4.2 表的别名

1.好处

(1)使用别名可以简化查询。

(2)使用表名前缀可以提高执行效率。

2.案例实操

合并员工表和部门表

 

3.4.3 内连接

内连接:只有进行连接的两个表中都存在与连接条件相匹配的数据才会被保留下来。

select e.empno,e.ename,d.dname from emp e,dept d where e.deptno=d.deptno;

select e.empno,e.ename,d.dname from emp e join dept d on e.deptno=d.deptno;

select e.empno,e.ename,d.dname from emp e inner join dept d on e.deptno=d.deptno;

3.4.4 左外连接

左外连接:JOIN操作符左边表中符合WHERE子句的所有记录将会被返回。

select e.empno,e.ename,d.dname from emp e left join dept d on e.deptno=d.deptno where e.ename='SMITH';

emp表中的数据全部显示出来

select e.empno,e.ename,d.dname from emp e right join dept d on e.deptno=d.deptno;

dept表中的数据全部显示出来

3.4.5 右外连接

右外连接:JOIN操作符右边表中符合WHERE子句的所有记录将会被返回。

select e.empno,e.ename,d.dname from dept d right join emp e on d.deptno=e.deptno;

emp表中的数据全部显示出来

select e.empno,e.ename,d.dname from dept d left join emp e on d.deptno=e.deptno;

dept表中的数据全部显示出来

3.4.6 全外连接

全外连接:将会返回所有表中符合WHERE语句条件的所有记录。如果任一表的指定字段没有符合条件的值的话,那么就使用NULL值替代。

select e.empno,e.ename,d.dname from emp e full join dept d on e.deptno=d.deptno;

3.4.7 多表连接

注意:连接 n个表,至少需要n-1个连接条件。例如:连接三个表,至少需要两个连接条件。

数据准备 location。txt

 

1.创建位置表

create table if not exists default.location(
loc int,
loc_name string
)
row format delimited fields terminated by '\t';

2.导入数据

hive (default)> load data local inpath '/opt/module/datas/location.txt' into table default.location;
  1. 多表连接查询
select e.ename,d.dname,l.loc_name from emp e join dept d on e.deptno=d.deptno

join location l on d.loc = l.loc ;

3.4.8 笛卡尔积

1.笛卡尔集会在下面条件下产生

(1)省略连接条件

(2)连接条件无效

(3)所有表中的所有行互相连接

2.案例实操

select e.ename,d.dname from emp e join dept d ;

3.4.9 连接谓词中不支持or

hive (default)> select e.empno, e.ename, d.deptno from emp e join dept d on e.deptno

= d.deptno or e.ename=d.ename;   # 错误的

3.5 排序

3.5.1 全局排序(Order By)

order By:全局排序,一个MapReduce

1.使用 ORDER BY 子句排序

ASC(ascend): 升序(默认) 

DESC(descend): 降序

2.ORDER BY 子句在SELECT语句的结尾

3.案例实操

(1)查询员工信息按工资升序排列

hive (default)> select * from emp order by sal;

(2)查询员工信息按工资降序排列

hive (default)> select * from emp order by sal desc;

3.5.2 按照别名排序

按照员工薪水的2倍排序

select ename,sal, sal *2 twosal  from emp order by twosal;  

3.5.3 多个列排序

按照部门和工资升序排序

select * from emp order by deptno ,sal;

3.5.4 每个MapReduce内部排序(Sort By)

sort By:每个MapReduce内部进行排序,对全局结果集来说不是排序。

1.设置reduce个数

hive (default)> set mapreduce.job.reduces=3;

2.查看设置reduce个数

hive (default)> set mapreduce.job.reduces;

3.根据员工编号降序查看员工信息

hive (default)> select * from emp sort by empno desc;

4.将查询结果导入到文件中(按照部门编号降序排序)

insert overwrite local directory '/opt/module/datas/sort-by'
row format delimited fields terminated by '\t'
select * from emp sort by empno desc;

3.5.5 分区排序(Distribute By)

Distribute By:类似MR中partition,进行分区,结合sort by使用。

注意,Hive要求DISTRIBUTE BY语句要写在SORT BY语句之前。

对于distribute by进行测试,一定要分配多reduce进行处理,否则无法看到distribute by的效果。

案例实操:

先按照部门编号分区,再按照员工编号降序排序。

hive (default)> set mapreduce.job.reduces=3;
insert overwrite local directory '/opt/module/datas/distribute-by'
row format delimited fields terminated by '\t'
select * from emp distribute by deptno sort by empno desc;

3.5.6 Cluster By

当distribute by和sorts by字段相同时,可以使用cluster by方式。cluster by除了具有distribute by的功能外还兼具sort by的功能。但是排序只能是倒序排序,不能指定排序规则为ASC或者DESC。

以下两种写法等价:

hive (default)> select * from emp cluster by deptno;

hive (default)> select * from emp distribute by deptno sort by deptno;

注意:按照部门编号分区,不一定就是固定死的数值,可以是20号和30号部门分到一个分区里面去。

3.6 分桶及抽样查询

hive 分区表:就是把大量的文件分区(子目录)存放,提高查询效率。

3.6.1 分桶表数据存储

分区针对的是数据的存储路径;分桶针对的是数据文件。

分区提供一个隔离数据和优化查询的便利方式。不过,并非所有的数据集都可形成合理的分区,特别是之前所提到过的要确定合适的划分大小这个疑虑。

分桶是将数据集分解成更容易管理的若干部分的另一个技术。

1.先创建分桶表,通过直接导入数据文件的方式

(1)数据准备 stu_buck.txt

 

(2)创建分桶表

create table stu_buck(id int, name string)
clustered by(id) 
into 4 buckets
row format delimited fields terminated by '\t';

(3)查看表结构

hive (default)> desc formatted stu_buck;

Num Buckets:            4     

(4)导入数据到分桶表中

hive (default)> load data local inpath '/opt/module/datas/stu_buck.txt' into table

 stu_buck;

(5)查看创建的分桶表中是否分成4个桶,如图6-7所示

发现并没有分成4个桶。是什么原因呢?

2.创建分桶表时,数据通过子查询的方式导入

(1)先建一个普通的stu表

create table stu(id int, name string)
row format delimited fields terminated by '\t';

(2)向普通的stu表中导入数据

load data local inpath '/opt/module/datas/stu_buck.txt' into table stu;

(3)清空stu_buck表中数据

truncate table stu_buck;
select * from stu_buck;

(4)导入数据到分桶表,通过子查询的方式

insert into table stu_buck
select id, name from stu;

(5)发现还是只有一个分桶,如图所示:

 

(6)需要设置一个属性

hive (default)> set hive.enforce.bucketing=true;
hive (default)> set mapreduce.job.reduces=-1;
hive (default)> insert into table stu_buck
select id, name from stu;

(7)查询分桶的数据

hive (default)> select * from stu_buck;
OK
stu_buck.id     stu_buck.name
1004    ss4
1008    ss8
1012    ss12
1016    ss16
1001    ss1
1005    ss5
1009    ss9
1013    ss13
1002    ss2
1006    ss6
1010    ss10
1014    ss14
1003    ss3
1007    ss7
1011    ss11
1015    ss15

3.6.2 分桶抽样查询

对于非常大的数据集,有时用户需要使用的是一个具有代表性的查询结果而不是全部结果。Hive可以通过对表进行抽样来满足这个需求。

查询表stu_buck中的数据:

hive (default)> select * from stu_buck tablesample(bucket 1 out of 4 on id);

注:tablesample是抽样语句,语法:TABLESAMPLE(BUCKET x OUT OF y) 。

y必须是table总bucket数的倍数或者因子。hive根据y的大小,决定抽样的比例。例如,table总共分了4份,当y=2时,抽取(4/2=)2个bucket的数据,当y=8时,抽取(4/8=)1/2个bucket的数据。

x表示从哪个bucket开始抽取,如果需要取多个分区,以后的分区号为当前分区号加上y。例如,table总bucket数为4,tablesample(bucket 1 out of 2),表示总共抽取(4/2=)2个bucket的数据,抽取第1(x)个和第3(x+y)个bucket的数据。

注意:x的值必须小于等于y的值,否则报错:

FAILED: SemanticException [Error 10061]: Numerator should not be bigger than denominator in sample clause for table stu_buck

3.7 其他常用查询函数

3.7.1 空字段赋值

函数说明

NVL:给值为NULL的数据赋值,它的格式是NVL( string1, replace_with)。它的功能是如果string1为NULL,则NVL函数返回replace_with的值,否则返回string1的值,如果两个参数都为NULL ,则返回NULL。

数据准备:采用员工表

查询:如果员工的comm为NULL,则用-1代替

hive (default)> select nvl(comm,-1) from emp;
OK
_c0
20.0
300.0
500.0
-1.0
1400.0
-1.0
-1.0
-1.0
-1.0
0.0
-1.0
-1.0
-1.0
-1.0

查询:如果员工的comm为NULL,则用领导id代替

hive (default)> select nvl(comm,mgr) from emp;
OK
_c0
20.0
300.0
500.0
7839.0
1400.0
7839.0
7839.0
7566.0
NULL
0.0
7788.0
7698.0
7566.0

1.7.2 CASE WHEN

1. 数据准备

name

dept_id

sex

八戒

A

猴哥

A

松松

B

 

 

凤姐

A

小可爱

B

萌萌

B

2.需求

求出不同部门男女各多少人。结果如下:

A     2       1

B     1       2

3.创建本地emp_sex.txt,导入数据

[root@hadoop003 datas]$ vi emp_sex.txt

八戒 A 男
猴哥 A 男
松松 B 男
凤姐 A 女
小可爱 B 女
萌萌 B 女

4.创建hive表并导入数据

create table emp_sex(
name string,
dept_id string,
sex string)
row format delimited fields terminated by "\t";
load data local inpath '/opt/module/datas/emp_sex.txt' into table emp_sex;

5.  按需求查询数据

select dept_id,sum(case sex when '男' then 1 else 0 end) sumnan,sum(case sex when '女' then 1 else 0 end) sumnv from emp_sex group by dept_id ;

3.7.3 行转列

1.相关函数说明

CONCAT(string A/col, string B/col…):返回输入字符串连接后的结果,支持任意个输入字符串;

CONCAT_WS(separator, str1, str2,...):它是一个特殊形式的 CONCAT()。第一个参数剩余参数间的分隔符。分隔符可以是与剩余参数一样的字符串。如果分隔符是 NULL,返回值也将为 NULL。这个函数会跳过分隔符参数后的任何 NULL 和空字符串。分隔符将被加到被连接的字符串之间;

select concat_ws('|',job,ename),deptno from emp;//能够处理数组

COLLECT_SET(col):函数只接受基本数据类型,它的主要作用是将某字段的值进行去重汇总,产生array类型字段。

select collect_set(job) from emp;  结果放在数组里面 ["CLERK","SALESMAN","MANAGER","ANALYST","PRESIDENT"]

类似于select  distinct job from emp;只不过distinct的结果放在多行了。

select concat_ws(':',collect_set(job)) from emp;

 

2.数据准备

name

constellation

blood_type

八戒

白羊座

A

猴哥

射手座

A

松松

白羊座

B

猪八戒

白羊座

A

凤姐

射手座

A

3.需求

把星座和血型一样的人归类到一起。结果如下:

射手座,A            猴哥|凤姐

白羊座,A            八戒|猪八戒

白羊座,B            松松

4.创建本地person.txt,导入数据 (注意用tab键分隔,不要直接复制)

[root@hadoop003 datas]$ vi person.txt

八戒 白羊座 A

猴哥      射手座 A

松松      白羊座 B

猪八戒    白羊座 A

凤姐      射手座 A

5.创建hive表并导入数据

create table person_info(
name string,
xingzuo string,
blood_type string)
row format delimited fields terminated by "\t";
load data local inpath "/opt/module/datas/person.txt" into table person_info;
  1. 按需求查询数据
select concat_ws(',',xingzuo,blood_type) base, name from person_info


select tt.base,collect_set(tt.name ) from tt group by tt.base;


select tt.base,collect_set(tt.name ) from (select concat_ws(',',xingzuo,blood_type) base, name from person_info) tt group by tt.base;

select tt.base,concat_ws('|',collect_set(tt.name )) from (select concat_ws(',',xingzuo,blood_type) base, name from person_info) tt group by tt.base;

行转列实现思路:

3.7.4 列转行

1.函数说明

EXPLODE(col):将Hive一中复杂的array或者map结构拆分成多行。

LATERAL VIEW 侧视图

用法:LATERAL VIEW udtf(expression) tableAlias AS columnAlias

解释:用于和split, explode等UDTF一起使用,它能够将一列数据拆成多行数据,在此基础上可以对拆分后的数据进行聚合。

2.数据准备

movie

category

《福尔摩斯》

悬疑,动作,科幻,剧情

《无间道》

悬疑,警匪,动作,心理,剧情

《红海行动》

战争,动作,灾难

3.需求

将电影分类中的数组数据展开。结果如下:

《福尔摩斯》      悬疑

《福尔摩斯》      动作

《福尔摩斯》      科幻

《福尔摩斯》      剧情

《无间道》   悬疑

《无间道》   警匪

《无间道》   动作

《无间道》   心理

《无间道》   剧情

《红海行动》        战争

《红海行动》        动作

《红海行动》        灾难

4.创建本地movie.txt,导入数据

[root@hadoop003 datas]$ vi movie.txt

《福尔摩斯》 悬疑,动作,科幻,剧情

《无间道》 悬疑,警匪,动作,心理,剧情

《红海行动》 战争,动作,灾难

5.创建hive表并导入数据

create table movie_info(
    movie string,
    category array<string>)
row format delimited fields terminated by "\t"
collection items terminated by ",";
load data local inpath "/opt/module/datas/movie.txt" into table movie_info;

6.  按需求查询数据

select movie,cate
from movie_info
lateral view explode(category) temp as cate;

四、函数

4.1 系统内置函数

1.查看系统自带的函数

hive> show functions;

2.显示自带的函数的用法

hive> desc function upper;

3.详细显示自带的函数的用法

hive> desc function extended upper;

4.2 自定义函数

1)Hive 自带了一些函数,比如:max/min等,但是数量有限,自己可以通过自定义UDF来方便的扩展。

2)当Hive提供的内置函数无法满足你的业务处理需要时,此时就可以考虑使用用户自定义函数(UDF:user-defined function)。

3)根据用户自定义函数类别分为以下三种:

(1)UDF(User-Defined-Function)

        一进一出   select upper(“DD”) from emp;

(2)UDAF(User-Defined Aggregation Function)

        聚集函数,多进一出

        类似于:count/max/min

(3)UDTF(User-Defined Table-Generating Functions)

        一进多出

        如lateral view explore()

4)官方文档地址

     https://cwiki.apache.org/confluence/display/Hive/HivePlugins

5)编程步骤:

(1)继承org.apache.hadoop.hive.ql.UDF

(2)需要实现evaluate函数;evaluate函数支持重载

(3)在hive的命令行窗口创建函数

a)添加jar

add jar linux_jar_path

b)创建function,

create [temporary] function [dbname.]function_name AS class_name;

(4)在hive的命令行窗口删除函数

Drop [temporary] function [if exists] [dbname.]function_name;

6)注意事项

UDF必须要有返回类型,可以返回null,但是返回类型不能为void;

4.3 自定义UDF函数

1.创建一个Maven工程Hive

2.导入依赖

<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.hive/hive-exec -->
    <dependency>
        <groupId>org.apache.hive</groupId>
        <artifactId>hive-exec</artifactId>
        <version>1.2.1</version>
    </dependency>
</dependencies>

3.创建一个类

package com.bigdata.hive;
import org.apache.hadoop.hive.ql.exec.UDF;

public class Lower extends UDF {

	public String evaluate (final String s) {
		
		if (s == null) {
			return null;
		}
		
		return s.toLowerCase();
	}
}

4.打成jar包上传到服务器/opt/module/jars/udf.jar

5.将jar包添加到hive的classpath

hive (default)> add jar /opt/module/jars/udf.jar;

6.创建临时函数与开发好的java class关联

hive (default)> create temporary function mylower as "com.bigdata.myhive.Lower";

7.即可在hql中使用自定义的函数mylower

hive (default)> select ename, mylower(ename) lowername from emp;

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值