MySQL操作表中的数据

164 阅读2分钟

对查询结果排序(ORDER BY)

order by 字段名 ASCDESC
'ASC'表示字段按升序排序;'DESC'表示字段按降序排序。其中'ASC'为默认值。
eg:
    select sno,sname,sclass from student where sclass = 1 order by sno;

image.png select sno,sname,sclass from student where sclass = 1 order by sno desc; image.png MARK

  • ORDER BY 关键字后可以跟子查询。
  • 当排序的字段中存在空值时,ORDER BY 会将该空值作为最小值来对待。
  • ORDER BY 指定多个字段进行排序时,MySQL 会按照字段的顺序从左到右依次进行排序

范围查询(BETWEEN AND)

between 取值1 and 取值2
-  取值1:表示范围的起始值。
-  取值2:表示范围的终止值。
eg:
    select sno,sname,sclass,sage from student where sage between 18 and 20;

image.png

分组查询(GROUP BY)

可以通过数据中的某一个或者多个字段进行分组
select 字段 from 表 where 条件 group by 字段1,字段2,字段3
若group by后的分组只有一个字段,那只会包含该字段的所有值,并不会包含所有选择查找字段的所有值

image.png

查询student1表中男生女生总人数
select name,count(*),sex from student1 group by sex;

image.png

过滤分组(HAVING)

where区别:
    select 字段 fromwhere 条件 group by 字段1,字段2,字段3       
    select 字段 from 表  group by 字段1,字段2,字段3 having 过滤条件
mark: 
- - where 根据数据表中的字段直接进行过滤,而 having 是根据前面已经查询出的字段进行过滤。
- - where 查询条件中不可以使用聚合函数,而 having 查询条件中可以使用聚合函数。
- - where 用于过滤数据行,而 having 用于过滤分组。
- - where 查询条件中不可以使用字段别名,而 having 查询条件中可以使用字段别名

eg:
    select sno,sname,sage from student group by sno having sage > 19;
    select sno,sname from student group by sno having sage > 19;

image.png

select sno,sname,sage from student where avg(sage)>20 group by sno;
select sno,sname,sage from student group by sno having avg(sage) > 19;

image.png