MySQL数据库之单表查询中关键字的执行顺序

MySQL数据库之单表查询中关键字的执行顺序


1 语法顺序

select 
distinct
from
where
group by
having
order by
limit

2 执行顺序

from            #step1 确定在哪张表做查询
where           #step2 设置过滤条件,过滤出符合条件的内容
group by        #step3 对过滤后的数据按字段分组
having          #step4 再进一步对分组后的数据过滤
select          #step5 查找数据
distinct        #step6 去重
order by        #step7 对去重后的数据按要求排序
limit           #step8 限制显示或打印数据的条数

1、正确且高效地查询数据的前提是:明确这些关键字的使用语法、语法顺序、执行顺序

2、语法顺序、执行顺序都是固定不能改变的,我们要按照MySQL的规则来使用

3、关键字的知识点较多且繁琐,需要我们灵活使用。

3 关键字使用语法

3.1 from

1、统计分析表中数据,第一步肯定是确定被统计的是那张表,使用关键字from,意为从该表中查数据

#示例
select * from student;   #从student表中查所有字段的数据

3.2 where

1、where使用在分组前,目的是过滤出需要统计待分析的那些数据

2、where在分组前,不能使用聚合函数,可以使用任意字段过滤

3、where可以使用的过滤条件包括:

  • 比较运算符,><>= <= <> !=
  • between and in 等关键字
  • 逻辑运算符,and or not
  • 模糊查询,like "pattren" , pattern 中有%表示任意读个字符,_表示一个字符
  • 正则表达式 regexp
#示例
from student where sname="jack";            #过滤出姓名为"jack"的学生
from student where sid>20;                  #过滤出学号大于20的学生们
from student where sid between 10 and 20;   #过滤出学号在10-20之间的学生们
from student where sid in (2,5,8);          #过滤出学号为2或者5或者8的学生
from student where sid >10 and sscore >90;  #过滤出学号大于10且分数大于90分的学生
from student where sname like "刘%";         #过滤出姓刘的学生们
from student where sname regexp "^刘";       #"刘"开头的,即姓刘的学生

3.3 group by

1、分组再where之后,是对过滤出来的数据再按要求的字段分组

2、group by 分组的目的是为了统计分析每个组内的数据信息,如班级人数,每个班级的平均分、男女人数等

3、分组后,只能使用分组字段、如果需要查看组内信息需要使用聚合函数

4、group by 还可以和group_concat()一块使用,查看组内成员信息

5、如果不适用group by,默认这张表示一个组

#示例
select class_name, count(sid) from student group by class_name;
select class_name,group_concat(sname) from student group by class_name;

3.4 having

1、having也是过滤的作用,但having用在分组后,是过滤组级别的

2、having与where不同,having只能使用分组字段或者是聚合函数,不能使用其他字段

3、where使用的那些过滤方式,having 也适用

#示例
select class_id,count(sid) from student group by class_id having class_id >10;
select class_id,count(sid) from student group by class_id having avg(score)>60;

3.5 select

1、select是选择数据的意思,后面直接更想要显示的数据字段,可以用聚合函数,如果是* 代表所有字段

3.6 distinct

1、distinct 去重的功能

#示例
select distinct course_name from student group by course_name;
#目的是统计有个不同的班级,因为存在不同的学生在一个班级,不使用distinct显示不美观

3.7 order by

1、order by 是对上述确定的数据做排序,分升序和降序两种

2、默认升序排列

#示例
select * from student order by sid asc;     #学号升序排列,此时可省略关键字 asc
select *from student order by score desc;   #分数降序排列

3.8 limit

1、限制查询的记录数

2、limit后面直接跟一个数字n,表示显示n条记录

3、limit后面分别跟两个数字n1,n2,表示从n1位置开始,显示n1位置后面的n2条记录

#示例
select sid from student limit 5;        #显示5条记录,sid分别为:1\2\3\4\5
select sid from student limit 0,5;      #显示5条记录,sid分别为:1\2\3\4\5,默认从0开始
select sid from student limit 1,5;      #显示5条记录,sid分别为:2\3\4\5\6

猜你喜欢

转载自www.cnblogs.com/liuxu2019/p/11434587.html
今日推荐