开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第30天,点击查看活动详情
SQL语句执行顺序:
(1) from、(2) join、(3) on、(4) where、(5) group by、
(6) avg、sum ...(组函数)、(7) having、(8) select、(9) distinct、(10) order by
结果去重
使用关键词:distinct
使用方法: distinct+要去重的字段
示例:select distinct university from user_profiledistinct 去重学校
查询结果限制返回行数
使用关键词:limit
使用方法:
limit n : 从第一条数据开始,取n条数据
limit m,n :从m+1条开始,取n条数据
limit n offset m:从m+1条开始,取n条数据
示例:SELECT device_id FROM user_profile LIMIT 0,2
用where过滤空值
使用关键词:not NULL或 某字段 !=''
使用方法: xxx is not null 或者 xxx !=''
示例:select device_id,gender,age,universityfrom user_profile where age is not NULL; select device_id,gender,age,university from user_profile where age !='';
限制范围
使用关键词:where in 和 Not in
使用方法: where in +(数值1,数值2,数值3.....) 和 Not in+(数值1,数值2,数值3.....)
示例:
select device_id,gender,age,university,gpa from user_profile where university in ('北京大学','复旦大学','山东大学')
select device_id,gender,age,university,gpa from user_profile where university not in ('清华大学')
模糊查询
使用关键词:like
使用方法: like+'xxx_' 匹配任意一个字符(一个下划线代表匹配一个,两个代表匹配两个) 或 like+'xxx%' 匹配0个或多个字符
示例:
SELECT device_id,age,university from user_profile where university like '%北京%'
SELECT device_id,age,university from user_profile where university like '北京__'
查找最值
使用关键词: max(要查找的字符) 或者 min(要查找的字段)
示例:
SELECT min(gpa) from user_profile
SELECT max(gpa) from user_profile
求平均值
使用关键词:avg(要平均的字段)
示例:
SELECT avg(gpa) from user_profile
保留小数
使用关键词: round(要保留的数值,要保留的位数)
示例:
select round (gpa,1) from user_profile
分组
使用关键词: group by + 要根据分组的字段
示例:
SELECT gpa from user_profile group by university
SELECT gpa from user_profile group by university,gender
分组后过滤
使用关键词: having + 过滤条件
解释:having 关键词 是对分组过后的数据进行再过滤 作用于组 而不是某个数据
示例:
select university,avg(question_cnt) as avg_question_cnt,avg(answer_cnt) as avg_answer_cnt from user_profile group by university having avg_question_cnt < 5 or avg_answer_cnt < 20
排序
使用关键词: order by + 要排序的字段 +asc 升序排列 (默认,可以省略 asc) 或者 order by + 要排序的字段 +desc 降序排列
示例:
select university,avg(question_cnt) as avg_question_cnt from user_profile group by university
order by avg_question_cnt asc