无需双重查询即可实现 MySQL 分页?

mysqlmysqli database

要使用 MySQL 分页,首先让我们了解如何使用 CREATE 命令并使用它来创建表。

mysql>CREATE table RowCountDemo
   -> (
   -> ID int,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.95 sec)

使用 INSERT 命令插入记录。

mysql>INSERT into RowCountDemo values(1,'Larry');
Query OK, 1 row affected (0.15 sec)

mysql>INSERT into RowCountDemo values(2,'John');
Query OK, 1 row affected (0.13 sec)

mysql>INSERT into RowCountDemo values(3,'Bela');
Query OK, 1 row affected (0.15 sec)

mysql>INSERT into RowCountDemo values(4,'Jack');
Query OK, 1 row affected (0.11 sec)

mysql>INSERT into RowCountDemo values(5,'Eric');
Query OK, 1 row affected (0.19 sec)

mysql>INSERT into RowCountDemo values(6,'Rami');
Query OK, 1 row affected (0.49 sec)

mysql>INSERT into RowCountDemo values(7,'Sam');
Query OK, 1 row affected (0.14 sec)

mysql>INSERT into RowCountDemo values(8,'Maike');
Query OK, 1 row affected (0.77 sec)

mysql>INSERT into RowCountDemo values(9,'Rocio');
Query OK, 1 row affected (0.13 sec)

mysql>INSERT into RowCountDemo values(10,'Gavin');
Query OK, 1 row affected (0.19 sec)

借助 SELECT 语句显示所有记录。

mysql>SELECT* from RowCountDemo;

以下是输出。

+------+-------+
| ID   | Name  |
+------+-------+
|    1 | Larry |
|    2 | John  |
|    3 | Bela  |
|    4 | Jack  |
|    5 | Eric  |
|    6 | Rami  |
|    7 | Sam   |
|    8 | Maike |
|    9 | Rocio |
|   10 | Gavin |
+------+-------+
10 rows in set (0.00 sec)

现在让我们看看无需重复查询的分页语法。

SELECT column_name From `yourTableName` WHERE someCondition LIMIT value1, value2;

现在应用上述语法。

mysql> SELECT ID,Name FROM `RowCountDemo` WHERE ID > 0 LIMIT 0, 11;

这是上述查询的输出。

+------+-------+
| ID   | Name  |
+------+-------+
|    1 | Larry |
|    2 | John  |
|    3 | Bela  |
|    4 | Jack  |
|    5 | Eric  |
|    6 | Rami  |
|    7 | Sam   |
|    8 | Maike |
|    9 | Rocio |
|   10 | Gavin |
+------+-------+
10 rows in set (0.00 sec)

相关文章