为了完成本关任务,你需要掌握:1. select
语法格式;2. 常用的select
语法。
select 语法格式
Hive select
操作的语法与SQL-92
规范几乎没有区别,其格式语法为:
SELECT [ALL | DISTINCT] select_expr,select_expr,… FROM table_reference
[WHERE where_condition] [GROUP BY col_list] [CLUSTER BY col_list | [DISTRIBUTE BY col_list] [SORT BY col_list]] [LIMIT number]
select 与各种属性的组合
-
简单的
select
查询操作,如下面的查询操作返回students
表中所有的行和列:hive> select * from students;
-
带
WHERE
子句的select
条件查询操作,返回满足WHERE
指定条件的行。如下面的查询操作返回用户信息表users
中的年龄大于10岁
且国籍为中国
的所有用户:
hive> select * from users where age > 10 and state = "China";
-
带
ALL
和DISTINCT
关键字的查询操作作用于确定是否返回重复的行,默认为ALL
,即select
查询返回重复的行:
hive> select coll,coll2 from t1;
1 3
1 3
1 4
2 5
hive> select distinct coll,coll2 from t1;
1 3
1 4
2 5
hive> select distinct coll from t1;
1
2
-
带
HAVING
关键字的查询操作用于代替复杂的子查询操作 如查询操作:hive> select coll from (select coll,sum(col2) as col2sum from t1 group by coll) t2 where t2.col2sum > 10;
可以替换为:
hive> select coll from t1 group by col1 having sum(col2) >10;
-
带
LIMIT
关键字的查询操作用于返回指定数目的满足条件的行(常用于返回Top k
问题)。返回满足条件的5
条记录,返回结果为从满足条件的记录中随机选取5
条。select * from t1 limit 5;
-
Top k
问题,返回满足条件的列按col1
降序排列的前5
条记录:select * from t1 sort by col1 desc limit 5;
编程要求
test2
数据库中student
表结构为:
INFO | TYPE | COMMENT |
---|---|---|
Sno | INT | student sno |
name | STRING | student name |
age | INT | student age |
sex | STRING | student sex |
score | STRUCT <Chinese:FLOAT,Math:FLOAT,English:FLOAT> | student score |
表中的数据为:
-
切换到
test2
数据库; -
查询
student
表中所有的行和列; -
查询年龄
age > 17
的女生female
; -
查询语文成绩
Chinese > 90
的记录; -
从
student
表中查询前3
条记录; -
返回按年龄降序的前
2
条记录。
--Begin
USE test2;
select * from student;
select * from student where age > 17 and sex = "female";
select * from student where score.Chinese > 90;
select * from student limit 3;
select * from student sort by age desc limit 2;
--End