為什麼在 MySQL SELECT 語句中允許使用“LIMIT 0”


眾所周知,如果在 MySQL SELECT 語句中使用 LIMIT 0,它會返回一個空集。

當希望從結果中獲取指定數量的行而不是所有行時,可以使用 LIMIT。如果你使用任何 MySQL API,那麼 LIMIT 的作用就是獲取結果列的型別。

LIMIT 0 可用於檢查查詢的有效性。詳情可使用以下連結 -

https://dev.mysql.com.tw/doc/refman/8.0/en/limit-optimization.html

以下是 LIMIT 0 的演示。用於建立表面的查詢如下 -

mysql> create table Limit0Demo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.61 sec)

現在,可以使用 insert 命令將某些記錄插入表中。查詢如下 -

mysql> insert into Limit0Demo(Name) values('David');
Query OK, 1 row affected (0.13 sec)
mysql> insert into Limit0Demo(Name) values('Larry');
Query OK, 1 row affected (0.24 sec)
mysql> insert into Limit0Demo(Name) values('Carol');
Query OK, 1 row affected (0.17 sec)
mysql> insert into Limit0Demo(Name) values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into Limit0Demo(Name) values('John');
Query OK, 1 row affected (0.11 sec)
mysql> insert into Limit0Demo(Name) values('Sam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into Limit0Demo(Name) values('James');
Query OK, 1 row affected (0.12 sec)
mysql> insert into Limit0Demo(Name) values('Maxwell');
Query OK, 1 row affected (0.13 sec)
mysql> insert into Limit0Demo(Name) values('Ricky');
Query OK, 1 row affected (0.09 sec)
mysql> insert into Limit0Demo(Name) values('Adam');
Query OK, 1 row affected (0.06 sec)

現在,可以使用 select 語句從表中顯示所有記錄。查詢如下 -

mysql> select *from Limit0Demo;

以下是輸出 -

+----+---------+
| Id | Name    |
+----+---------+
|  1 | David   |
|  2 | Larry   |
|  3 | Carol   |
|  4 | Bob     |
|  5 | John    |
|  6 | Sam     |
|  7 | James   |
|  8 | Maxwell |
|  9 | Ricky   |
| 10 | Adam    |
+----+---------+
10 rows in set (0.00 sec)

案例 1:使用 limit 0。

查詢如下 -

mysql> select *from Limit0Demo limit 0;
Empty set (0.00 sec)

案例 2:當你希望從表中獲取特定數量的行時。查詢如下 -

mysql> select *from Limit0Demo limit 3;

以下是輸出 -

+----+-------+
| Id | Name  |
+----+-------+
|  1 | David |
|  2 | Larry |
|  3 | Carol |
+----+-------+
3 rows in set (0.00 sec)

更新於: 2019-07-30

818 次瀏覽

啟動你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.