在單個查詢中同時實現 MySQL 的 LIMIT 和 OFFSET,並說明它們的區別


LIMIT 告訴你希望獲取多少條記錄,而 OFFSET 提供給定位置 +1 開始的記錄。我們先建立一個表 -

mysql> create table DemoTable
   -> (
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (1.33 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.27 sec)

mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.27 sec)

mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.26 sec)

mysql> insert into DemoTable values('Sam');
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable values('Mike');
Query OK, 1 row affected (0.59 sec)

mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.60 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select *from DemoTable;

輸出

將產生如下輸出 -

+--------+
| Name   |
+--------+
| John   |
| Chris  |
| David  |
| Bob    |
| Sam    |
| Mike   |
| Carol  |
| Robert |
+--------+
8 rows in set (0.00 sec)

以下是實現 MySQL 限制偏移量的查詢 -

mysql> select *from DemoTable limit 4 offset 3;

輸出

將產生如下輸出 -

+-------+
| Name  |
+-------+
| Bob   |
| Sam   |
| Mike  |
| Carol |
+-------+
4 rows in set (0.00 sec)

更新於: 30-6 月-2020

635 次瀏覽

啟動您的 職業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.