MySQL LIMIT 用於選擇單行


要選擇 MySQL 中的單行,可以使用 LIMIT。首先,讓我們建立一個表。建立表的查詢如下所示 -

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

使用插入命令在表中插入一些記錄。查詢如下所示 -

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Larry',24,98);
Query OK, 1 row affected (0.15 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('John',23,89);
Query OK, 1 row affected (0.21 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Mike',21,85);
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Sam',26,56);
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Carol',21,59);
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Bob',20,91);
Query OK, 1 row affected (0.21 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('David',28,93);
Query OK, 1 row affected (0.15 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下所示 -

mysql> select *from selectWithPrimaryKey;

以下為輸出 -

+----+-------+------+-------+
| Id | Name  | Age  | Marks |
+----+-------+------+-------+
| 1  | Larry | 24   | 98    |
| 2  | John  | 23   | 89    |
| 3  | Mike  | 21   | 85    |
| 4  | Sam   | 26   | 56    |
| 5  | Carol | 21   | 59    |
| 6  | Bob   | 20   | 91    |
| 7  | David | 28   | 93    |
+----+-------+------+-------+
7 rows in set (0.00 sec)

以下是使用 LIMIT 從表中選擇單行的查詢 -

mysql> select *from selectWithPrimaryKey where Id = 10 or Age = 29 or Marks = 89 limit 1;

以下為輸出 -

+----+------+------+-------+
| Id | Name | Age  | Marks |
+----+------+------+-------+
| 2  | John | 23   | 89    |
+----+------+------+-------+
1 row in set (0.00 sec)

更新日期:2020-06-30

427 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告