网站地图    收藏   

主页 > 后端 > mysql数据库 >

mysql选择上一条、下一条数据记录,排序上移、下

来源:自学PHP网    时间:2015-04-16 10:50 作者: 阅读:

[导读] 1 功能需要完成列表排序上移,下移,置顶功能!效果如下图所示:2设置思路设置一个rank为之间戳,通过选择上移,就是将本记录与上一条记录rank 20540;交换,下移就是将本条记录与下...

1.功能需要

完成列表排序上移,下移,置顶功能!效果如下图所示: \

2设置思路

设置一个rank为之间戳,通过选择上移,就是将本记录与上一条记录rank值交换,下移就是将本条记录与下一条记录rank值交换,置顶就是将本记录与rank值最小的记录交换

3.表数据结构

选择mysql记录上一条,下一条sql语句

SELECT * FROM user ORDER BY rank ASC

+----+------+---------+
| ID | rank | name    |
+----+------+---------+
|  1 |    1 | admin1  |
|  2 |    2 | admin2  |
|  3 |    3 | admin3  |
|  4 |    4 | admin4  |
|  5 |    5 | admin5  |
|  6 |    6 | admin6  |
|  7 |    7 | admin7  |
|  8 |    8 | admin8  |
|  9 |    9 | admin9  |
| 10 |   10 | admin10 |
| 11 |   11 | admin11 |
| 12 |   12 | admin12 |
+----+------+---------+


4.选择上一行

select * from user where id <3 or id=(SELECT MIN(id) from user) order by id desc limit 1

+----+------+--------+
| ID | rank | name   |
+----+------+--------+
|  2 |    2 | admin2 |
+----+------+--------+
1 row in set (0.00 sec)

5.当id=1时

mysql> select * from user where id <1 or id=(SELECT MIN(id) from user) order by id desc limit 1;
+----+------+--------+
| ID | rank | name   |
+----+------+--------+
|  1 |    1 | admin1 |
+----+------+--------+
1 row in set (0.00 sec)

6.选择下一行

mysql> select * from user where id > 3 OR ID=(SELECT MAX(ID) FROM user) ORDER BY id ASC LIMIT 1;
+----+------+--------+
| ID | rank | name   |
+----+------+--------+
|  4 |    4 | admin4 |
+----+------+--------+
1 row in set (0.00 sec)

7.当id为最大值时

mysql> select * from user where id > 12 OR ID=(SELECT MAX(ID) FROM user) ORDER BY id ASC LIMIT 1;
+----+------+---------+
| ID | rank | name    |
+----+------+---------+
| 12 |   12 | admin12 |
+----+------+---------+
1 row in set (0.00 sec)




自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习

京ICP备14009008号-1@版权所有www.zixuephp.com

网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com

添加评论