基本查询
- 全表数据查询:
> select * from testtable;

Hive查询01.png
- 特定列查询:
> select name from testtable;

Hive查询02.png
- 语句大小写不敏感,可以全写在一行,也可以写在多行。
- 关键字不能被缩写,也不能分行。
- 使用缩进提高可读性,各子句一般分行写。
- 列别名:
> select name AS nickname from testtable;

Hive查询03.png
- 重命名一个列,可以便于计算。
- 写法上可以别名紧跟列名,也可以在列明和别名间使用关键字“AS”,推荐使用关键字写法。
- 算术运算符:
> select age +1 from testtable;
运算符 |
描述 |
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按位取反 |
- 常用函数
> select count(*) name from testtable;

Hive查询04.png
> select max(age) max_age from testtable;

Hive查询05.png
> select min(age) min_age from testtable;

Hive查询06.png
> select sum(age) sum_age from testtable;

Hive查询07.png
> select avg(age) avg_age from testtable;

Hive查询08.png
- Limit限制查询结果返回的行数:
> select * from testtable limit 2;

Hive查询18-limit.png
Where语句
- Where
> select * from testtable where age > 19;

Hive查询19-where.png
Where语句过滤不满足条件的结果。
- 比较运算符
操作符 |
支持的数据类型 |
描述 |
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[NUM1,NUM2] |
所有数据类型 |
使用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中的正则表达式接口实现的,因为正则也依据其中的规则 |
> select * from testtable where age=20;

Hive查询09.png
> select * from testtable where age between 15 and 19;

Hive查询10.png
select * from testtable where name is null;

Hive查询11.png
> select * from testtable where age in (15,20);

Hive查询12.png
- Like和RLike
查找name中以‘D’开头的名字:
> select * from testtable where name like 'D%';

Hive查询13.png
查找name中含有‘D’的名字:
> select * from testtable where name rlike '[D]';

Hive查询14.png
- 逻辑运算符
操作符 |
含义 |
AND |
逻辑并 |
OR |
逻辑或 |
NOT |
逻辑否 |
> select * from testtable where name='Snow' and age>18;

Hive查询15.png
> select * from testtable where name='Snow' or age>18;

Hive查询16.png
> select * from testtable where age not in (19,20);

Hive查询17.png
网友评论