电商中:我们想查看今天所有成交的订单,按照交易额从高到低排序,此时我们可以使用数据库中的排序。
排序语法:
select 字段名 from 表名 order by 字段1 [asc|desc], 字段2 [asc|desc];
需要排序的字段跟在order by之后;
asc|desc 表示排序的规则,asc:升序 desc:降序 默认为升序asc;
支持多个字段进行排序,多字段排序之间用逗号隔开
单字段排序:
select * from test2 order by a asc;
select * from test2 order by a desc;
多字段排序:
比如学生表,先按学生年龄降序,年龄相同时,再按学号升序,eg:

mysql>select * from stu order by age desc, id asc;

按别名排序:
mysql> select age '年龄', id as '学号' from stu order by 年龄 asc, 学号 desc;

按函数排序:
有学生表(id:编号, birth:出生日期,name:姓名)

需求:
按照出生年份升序,编号升序,查询出编号,出生日期,出生年份,姓名,2种写法:
mysql> select id '编号', birth '出生日期', year(birth) '出生年份', name as '姓名' from student order by year(birth), id ;

mysql> select id '编号', birth '出生日期', year(birth) '出生年份', name as '姓名' from student order by 出生年份, 编号 ;

说明:
year函数,属于日期函数,可以获取对应日期种的年份
where之后进行排序
有订单数据如下:

需求:
查询订单金额>=100的,按照订单金额降序排序,显示2列数据,列头:订单编号、订单金额:
mysql> select id '订单编号', price as '订单金额' from t_order where price>=100 order by price desc;

limit介绍
limit用来限制select查询返回的行数,常用于分页等操作。
语法:
select 列 from 表 limit [offset,] count;
说明:
offset:表示偏移量,通俗点讲就是跳过多少行,offset可以省略,默认为0,表示跳过0行,范围:0到正无穷
count:跳过offset行之后开始取数据,取count行记录,范围:0到正无穷
获取前n行记录:
select 列 from 表 limit 0,n;
或者
select 列 from 表 limit n;

eg:获取订单的前2条记录
mysql> select * from t_order limit 2;

获取最大的一条记录
我们需要获取订单金额最大的一条记录,可以这么做:先按照金额降序,然后取第一条记录
mysql> select id '订单编号', price as '订单金额' from t_order order by price desc limit 1;

获取排名n到m的记录
语法:需要先跳过n-1条记录,然后取m-m+1条记录
select 列 from 表 limit n-1,m-n+1;
eg:获取订单金额最高的3到5的记录
先跳过2条,取3条记录

分页查询
分页经常使用,一般2个参数:
page: 表示第几页,从1开始,范围1到正无穷
pageSize:每页显示多少条记录,范围1到正无穷
如:page=2,pageSize=10,表示获取第2页10条数据
使用limit实现分页,语法:
select 列 from 表名 limit (page - 1) * pageSize,pageSize;
需求:我们按照订单金额降序,每页显示2条,依次获取所有订单数据、第1页,第2页、第3页数据,如下:

第一页:

第二页:

第四页:

***避免踩坑
limit中不能使用表达式

limit后面的2个数字不能为负数

排序分页存在的坑:
***当排序中存在相同的值时,需要再指定一个排序规则
总结
-
order by…[asc|desc]用于对查询结果排序,asc:升序,desc:降序,默认为升序
-
limit 用来限制查询结果返回的行数,有2个参数(offset,cont)offset:表示跳过多少行,count:表示跳过offset行之后取count行
-
limit中的offset可以省略,默认值为0
-
limit中offset和count都必须大于等于0
-
limit中offset和count的值不能用表达式
-
分页排序时,排序不要有二义性,二义性情况下可能导致分页结果乱序,可以在后面追加一个主键排序,比如有相同值的情况下
网友评论