一:排序数据记录数据:
1.按照单字段排序:
(1):升序排序:
select 字段
from 表名
order by 字段 asc;
例如: select name from students order by age asc;
表示从学生中按年龄升序查询学生年龄,若不指定asc或者desc 默认升序;
(2):降序排序:
select 字段
from 表名
order by 字段 desc;
例如:select name from students order by age desc;
同上,不过是以降序;
2:按照多字段排序:
select 字段
from 表名
order by 字段1 asc|desc,
字段2 asc|desc;
例如:
select name from students
order by age asc,
score desc;
表示从学生中按照年龄升序,成绩降序查询姓名;(若年龄相同,则按成绩降序排列)
二:限制数据查询记录数量
select 字段1,字段2,字段3
from 表名
where condition
limit offset_start,row_count;
(1):不指定初始位置:
select name from students limit 2;
设置查询数量为2;
(2):指定初始位置:
select name from students limit 0,5;
表示从第0条数据开始查询,查询5条(与数组一样,都时从0开始);
三:统计函数和分组数据记录查询:
函数:
count(),查询表中记录条数。
avg(字段), 查询表中字段值的平均值。
sum(),查询表中字段值的总和。
max(),min(),查询字段中值的最大|最小值。
(1):MYSQL支持的统计函数:
select function(字段)
from 表名
where condition;
例如:select count(name) from students;
表示统计学生中name字段的数量。
select name from students where age>18;
表示统计学生中大于18岁name字段的个数。
(2):统计计算平均值:
select avg(age) from students;
统计学生中年龄的平均值。
(3):统计最大,最小值:
select max(age)|min(age) from students;
四.分组查询:
(1): select function()
from 表名
where condition
group by 字段:
表示以字段分组,字段相同的一组,然后查询;
例如:
select * from students group by name;
表示以名字为组,查询所有字段,若名字相同的有几个,则显示第一个。
(2):实现having子句限定分组查询:
select function()
from students
where condition
group by 字段1,字段2
having condition;
例如:
select name from students
group by age
having score >60;
(3):group_concat(字段)能把同一组的所有这个字段显示出来;
例如:
select group_concat(name)
from students;
group by score;