在 MySQL 中跳过每 2 行后选择下一行


要跳过行,您可以使用 OFFSET。我们首先创建一个表 -

mysql> create table DemoTable617(Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,FirstName varchar(100));
Query OK, 0 rows affected (1.70 sec)

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

mysql> insert into DemoTable617(FirstName) values('John');
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable617(FirstName) values('Sam');
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable617(FirstName) values('Carol');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable617(FirstName) values('Mike');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable617(FirstName) values('David');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable617(FirstName) values('Bob');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable617(FirstName) values('Robert');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable617(FirstName) values('Chris');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable617(FirstName) values('Mike');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable617(FirstName) values('Adam');
Query OK, 1 row affected (0.49 sec)

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

mysql> select *from DemoTable617;

这将产生以下输出 -

+----+-----------+
| Id | FirstName |
+----+-----------+
| 1 | John       |
| 2 | Sam        |
| 3 | Carol      |
| 4 | Mike       |
| 5 | David      |
| 6 | Bob        |
| 7 | Robert     |
| 8 | Chris      |
| 9 | Mike       |
| 10| Adam      |
+----+-----------+
10 rows in set (0.00 sec)

以下是选择行的查询。首先按 DESC 排序。然后,它将跳过两行,并使用 LIMIT 5 显示 5 行 -

mysql> select tbl.* from (select *from DemoTable617 order by FirstName DESC LIMIT 5 OFFSET 2) AS tbl ORDER BY tbl.Id
;

这将产生以下输出 -

+----+-----------+
| Id | FirstName |
+----+-----------+
| 1 | John       |
| 4 | Mike       |
| 5 | David      |
| 8 | Chris      |
| 9 | Mike       |
+----+-----------+
5 rows in set (0.00 sec)

更新于: 23-8-2019

382 次浏览

开启你的 职业生涯

完成课程,获取认证

开始
广告