在 MySQL 中获取特定限制后的有序记录


为此,你可以使用子查询。首先,让我们创建一个表 -

mysql> create table DemoTable618 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,StudentFirstName varchar(100)
);
Query OK, 0 rows affected (1.45 sec)

使用插入命令在表中插入一些记录 -

mysql> insert into DemoTable618(StudentFirstName) values('David');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable618(StudentFirstName) values('Chris');
Query OK, 1 row affected (0.44 sec)
mysql> insert into DemoTable618(StudentFirstName) values('Robert');
Query OK, 1 row affected (0.54 sec)
mysql> insert into DemoTable618(StudentFirstName) values('Sam');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable618(StudentFirstName) values('Mike');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable618(StudentFirstName) values('Carol');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable618(StudentFirstName) values('Bob');
Query OK, 1 row affected (3.66 sec)
mysql> insert into DemoTable618(StudentFirstName) values('John');
Query OK, 1 row affected (0.17 sec)

使用选择语句从表中显示所有记录 -

mysql> select *from DemoTable618;

这将产生以下输出 -

+-----------+------------------+
| StudentId | StudentFirstName |
+-----------+------------------+
|         1 | David            |
|         2 | Chris            |
|         3 | Robert           |
|         4 | Sam              |
|         5 | Mike             |
|         6 | Carol            |
|         7 | Bob              |
|         8 | John             |
+-----------+------------------+
8 rows in set (0.00 sec)

以下是获取特定限制后的有序记录的查询 -

mysql> select *from (select StudentId,StudentFirstName from DemoTable618 where StudentId >= 5 order by StudentId limit 4) tbl order by tbl.StudentId desc;

这将产生以下输出 -

+-----------+------------------+
| StudentId | StudentFirstName |
+-----------+------------------+
|         8 | John             |
|         7 | Bob              |
|         6 | Carol            |
|         5 | Mike             |
+-----------+------------------+
4 rows in set (0.00 sec)

更新日期:2019 年 8 月 23 日

83 次浏览

启动你的 事业

完成课程获取认证

开始学习
广告