Hive study notes six

Inquire

[WITH CommonTableExpression (, CommonTableExpression)*]    (Note: Only available starting with Hive 0.13.0)
SELECT [ALL | DISTINCT] select_expr, elect_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]

First, the basic query

1, all tables and queries specific columns
  • 1) Full-table query
hive (default)> select * from emp;
  • 2) select a particular column of the query
hive (default)> select empno, ename from emp;

Note:
(1) SQL language is not case sensitive.
(2) SQL can be written in one or more lines
(3) Keywords can not be abbreviated nor branch
(4) each clause generally branches write.
(5) the use of statements indented to improve readability.

2, column aliases
  • 1) Rename a column.

  • 2) ease of calculation.

  • 3) followed by a column name, you can also add the keyword 'AS' between the column names and aliases

  • 4) cases of practical operation

(1) query name and department

hive (default)> select ename AS name, deptno dn from emp;
3, arithmetic operator
Operators description
A+B A and B are added
A-B A minus B
A*B A and B are multiplied
A/B A divided by B
A%B A B I to take
A&B A and B are bit-wise with
A B
A^B A and B are bit-wise XOR
~A A bitwise

Case practical operation: check out the salaries for all employees plus 1 display.

hive (default)> select sal +1 from emp;
4, commonly used functions
  • 1) Find the total number of rows (count)
hive (default)> select count(*) cnt from emp;
  • 2) find the maximum salary (max)
hive (default)> select max(sal) max_sal from emp;
  • 3) Find the minimum wage (min)
hive (default)> select min(sal) min_sal from emp;
  • 4) the sum (sum) seeking wages
hive (default)> select sum(sal) sum_sal from emp; 
  • 5) Find the average salary (avg)
hive (default)> select avg(sal) avg_sal from emp;
5, Limit statement

A typical query returns multiple rows of data. LIMIT clause restricts the number of rows returned.

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

Two, Where statement

  • 1) WHERE clause, the row does not satisfy the conditions to filter out.

  • 2) WHERE clause immediately after the FROM clause.

  • 3) cases of practical operation

Check out all the staff salaries greater than 1000

hive (default)> select * from emp where sal >1000;
1, comparison operators (Between / In / Is Null)
  • 1) described in the table below predicates operators, these operators can also be used and HAVING JOIN ... ON statements.
Operators Supported data types description
A=B Basic data types If A is equal to B returns TRUE, return FALSE conversely
A<=>B Basic data types If A and B are both NULL, then returns TRUE, and consistent with the results of other equal sign (=) operator, if either result is NULL is NULL
A<>B, A!=B Basic data types A or B is NULL NULL is returned; if A does not equal B, then return TRUE, otherwise returns FALSE
A<B Basic data types A or B is NULL, NULL is returned; if A is smaller than B, TRUE is returned, otherwise it returns FALSE
A<=B Basic data types A or B is NULL, NULL is returned; if A or less B, TRUE is returned, otherwise returns FALSE
A>B Basic data types A or B is NULL, NULL is returned; if A is greater than B, TRUE is returned, otherwise it returns FALSE
A>=B Basic data types A or B is NULL, NULL is returned; if A is greater than or equal B, TRUE is returned, otherwise it returns FALSE
A [NOT] BETWEEN B AND C Basic data types If A, B or C according to any one of NULL, the result to NULL. If the value of A is greater than B and equal to or less C, then the result is TRUE, otherwise it is FALSE. If you use the NOT keyword can reach the opposite effect.
A IS NULL All data types If A is equal to NULL, then returns TRUE, return FALSE conversely
A IS NOT NULL All data types If A is not equal to NULL, then returns TRUE, return FALSE conversely
IN (value 1, value 2) All data types Values ​​using the IN operator display list
A [NOT] LIKE B STRING type B is a simple SQL under a regular expression, if A, then its matching, TRUE is returned; otherwise returns FALSE. Expression B is as follows: 'x%' denotes A must start with a letter 'x', '% x' expressed with a letter A 'x' end, while the '% x%' represented with the letter A 'x', It may be at the beginning, end or middle of the string. If you use the NOT keyword can reach the opposite effect.
A RLIKE B, A REGEXP B STRING type B is a regular expression, if its matching A, TRUE is returned; otherwise returns FALSE. Matching using regular expressions in JDK interface, because regular basis also rule them. For example, the regular expression must match the entire string, and A, not just its string matching.
  • 2) Case practical operation

(1) check out the salaries of all employees equal to 5000

hive (default)> select * from emp where sal =5000;

(2) query wage in the employee information 500-1000

hive (default)> select * from emp where sal between 500 and 1000;

(3) comm query information is empty of all employees

hive (default)> select * from emp where comm is null;

(4) query wages and employee information 1500 5000

hive (default)> select * from emp where sal IN (1500, 5000);
2、Like和RLike
  • 1) use the LIKE operator to select similar values

  • 2) the selection criteria may contain characters or numbers:

  % Represents zero or more characters (any characters).
  _ Represents one character.

  • 3) RLIKE Hive in this clause is an extension function, which can be expressions of this more powerful language to match the conditions specified by the Java positive.

  • 4) cases of practical operation

(1) Find the beginning of employee salary information 2

hive (default)> select * from emp where sal LIKE '2%';

(2) to find the second number is the salary of the employee information 2

hive (default)> select * from emp where sal LIKE '_2%';

(3) Find salary containing employee information 2

hive (default)> select * from emp where sal RLIKE '[2]';
3, logical operators (And / Or / Not)
Operators meaning
AND And logic
OR Logical or
NOT No logic

Case practical operation

(1) query salary greater than 1000, 30 departments

hive (default)> select * from emp where sal>1000 and deptno=30;

(2) query salary greater than 1000, or the department 30

hive (default)> select * from emp where sal>1000 or deptno=30;

(3) query employee information in addition to the 20 departments and 30 departments

hive (default)> select * from emp where deptno not IN(30, 20);

Third, grouping

1, Group By statement

  GROUP BY statement often used together and aggregate functions, grouped according to one or more of the queue result, and then perform the polymerization operation for each group.

Case practical operation:

The average wage (1) calculate the emp table for each department

hive (default)> select t.deptno, avg(t.sal) avg_sal from emp t group by t.deptno;

(2) calculate the maximum salary in each department emp each post

hive (default)> select t.deptno, t.job, max(t.sal) max_sal from emp t group by t.deptno, t.job;
2, Having Statement
  • 1) having different and where

(1) where to play a role for the columns in the table, query data; having to play a role for the query results columns, filter the data.
(2) write back where the packet can not function, and the packet may be used later having a function.
(3) having only a group by group statistics statement.

  • 2) Case practical operation:

(1) averaged greater than 2000 salary for each department of department

The average salary for each department seeking

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

The average salary for each department seeking more than 2,000 department

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

四、Join语句

1、等值Join

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

(1)根据员工表和部门表中的部门编号相等,查询员工编号、员工名称和部门编号;

hive (default)> select e.empno, e.ename, d.deptno, d.dname from emp e join dept d on e.deptno = d.deptno;
2、表的别名
  • 1)好处

(1)使用别名可以简化查询。
(2)使用表名前缀可以提高执行效率。

  • 2)案例实操

合并员工表和部门表

hive (default)> select e.empno, e.ename, d.deptno from emp e join dept d on e.deptno = d.deptno;
3、内连接

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

hive (default)> select e.empno, e.ename, d.deptno from emp e join dept d on e.deptno = d.deptno;
4、左外连接

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

hive (default)> select e.empno, e.ename, d.deptno from emp e left join dept d on e.deptno = d.deptno;
5、右外连接

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

hive (default)> select e.empno, e.ename, d.deptno from emp e right join dept d on e.deptno = d.deptno;
6、满外连接

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

hive (default)> select e.empno, e.ename, d.deptno from emp e full join dept d on e.deptno = d.deptno;
7、多表连接

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

  • 0)数据准备
1700	Beijing
1800	London
1900	Tokyo
  • 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;
  • 3)多表连接查询
hive (default)>SELECT e.ename, d.deptno, l. loc_name
FROM   emp e 
JOIN   dept d
ON     d.deptno = e.deptno 
JOIN   location l
ON     d.loc = l.loc;

  大多数情况下,Hive会对每对JOIN连接对象启动一个MapReduce任务。本例中会首先启动一个MapReduce job对表e和表d进行连接操作,然后会再启动一个MapReduce job将第一个MapReduce job的输出和表l;进行连接操作。
  注意:为什么不是表d和表l先进行连接操作呢?这是因为Hive总是按照从左到右的顺序执行的。

8、笛卡尔积
  • 1)笛卡尔集会在下面条件下产生:

(1)省略连接条件
(2)连接条件无效
(3)所有表中的所有行互相连接

2)案例实操

hive (default)> select empno, deptno from emp, dept;

FAILED: SemanticException Column deptno Found in more than One Tables/Subqueries

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;   错误的

五、排序

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;
2、按照别名排序

  按照员工薪水的2倍排序

hive (default)> select ename, sal*2 twosal from emp order by twosal;
3、多个列排序

  按照部门和工资升序排序

hive (default)> select ename, deptno, sal from emp order by deptno, sal ;
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)将查询结果导入到文件中(按照部门编号降序排序)
hive (default)> insert overwrite local directory '/opt/module/datas/sortby-result' select * from emp sort by deptno desc;
5、分区排序(Distribute By)

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

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

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

案例实操:
(1)先按照部门编号分区,再按照员工编号降序排序。

hive (default)> set mapreduce.job.reduces=3;
hive (default)> insert overwrite local directory '/opt/module/datas/distribute-result' select * from emp distribute by deptno sort by empno desc;
6、Cluster By

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

  • 1)以下两种写法等价
hive (default)> select * from emp cluster by deptno;
hive (default)> select * from emp distribute by deptno sort by deptno;

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

六、分桶及抽样查询

1、分桶表数据存储

  分区针对的是数据的存储路径;分桶针对的是数据文件。
  分区提供一个隔离数据和优化查询的便利方式。不过,并非所有的数据集都可形成合理的分区,特别是之前所提到过的要确定合适的划分大小这个疑虑。
  分桶是将数据集分解成更容易管理的若干部分的另一个技术。

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

(0)数据准备

1001	ss1
1002	ss2
1003	ss3
1004	ss4
1005	ss5
1006	ss6
1007	ss7
1008	ss8
1009	ss9
1010	ss10
1011	ss11
1012	ss12
1013	ss13
1014	ss14
1015	ss15
1016	ss16

(1)创建分桶表

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

(2)查看表结构

hive (default)> desc formatted stu_buck;
Num Buckets:            4     

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

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

(4)查看创建的分桶表中是否分成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/student.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
1001    ss1
1005    ss5
1009    ss9
1012    ss12
1016    ss16
1002    ss2
1006    ss6
1013    ss13
1003    ss3
1007    ss7
1010    ss10
1014    ss14
1004    ss4
1008    ss8
1011    ss11
1015    ss15
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开始抽取。例如,table总bucket数为4,tablesample(bucket 4 out of 4),表示总共抽取(4/4=)1个bucket的数据,抽取第4个bucket的数据。

  注意:x的值必须小于等于y的值,否则
FAILED: SemanticException [Error 10061]: Numerator should not be bigger than denominator in sample clause for table stu_buck

3、数据块抽样

  Hive提供了另外一种按照百分比进行抽样的方式,这种是基于行数的,按照输入路径下的数据块百分比进行的抽样。

hive (default)> select * from stu tablesample(0.1 percent) ;

  提示:这种抽样方式不一定适用于所有的文件格式。另外,这种抽样的最小抽样单元是一个HDFS数据块。因此,如果表的数据大小小于普通的块大小128M的话,那么将会返回所有行。

Guess you like

Origin www.cnblogs.com/nthforsth/p/12619078.html