在 MySQL 中選擇單行?


如果要基於主鍵選擇單行,請使用 WHERE 子句。語法如下所示 −

SELECT * FROM yourTableName WHERE yourPrimaryKeyColumnName = someValue;

為了理解以上語法,讓我們建立一個表。建立表的查詢如下 −

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)

使用 insert 命令在表中插入一些記錄。查詢如下 −

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)

以下是用於從表中選擇單行的查詢 −

mysql> select *from selectWithPrimaryKey where Id = 6;

以下是輸出 −

+----+------+------+-------+
| Id | Name | Age  | Marks |
+----+------+------+-------+
| 6  | Bob  | 20   | 91    |
+----+------+------+-------+
1 row in set (0.00 sec)

更新於: 30-Jul-2019

1K+ 瀏覽次數

開啟你的 職業

完成課程認證

開始學習
廣告