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

mysqlmysqli database

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

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

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

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)

使用 select 语句显示表中的所有记录 −

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)

相关文章