在 MySQL 中选择单行?

mysqlmysqli database

如果要根据主键选择单行,请使用 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)

相关文章