在 MySQL 中将查询结果设置为变量?

mysqlmysqli database

您可以使用 select into 命令设置查询结果。语法如下。

select yourColumnName1 into @anyVariableName from yourTableName where yourColumnName2='anyValue';

使用 select 命令检查结果是否存在于变量中。语法如下 -

select @anyVariableName;

为了理解上述语法,让我们首先创建一个表。创建表的查询如下。

mysql> create table StudentInformation
-> (
-> StudentId int,
-> StudentName varchar(100),
-> StudentAge int
-> );
Query OK, 0 rows affected (0.62 sec)

使用 insert 命令在表中插入一些记录。 查询语句如下。

mysql> insert into StudentInformation values(1,'John',23);
Query OK, 1 row affected (0.21 sec)

mysql> insert into StudentInformation values(2,'Adam',24);
Query OK, 1 row affected (0.17 sec)

mysql> insert into StudentInformation values(3,'Bob',21);
Query OK, 1 row affected (0.20 sec)

mysql> insert into StudentInformation values(4,'Carol',20);
Query OK, 1 row affected (0.17 sec)

mysql> insert into StudentInformation values(5,'Mike',25);
Query OK, 1 row affected (0.13 sec)

使用 select 语句显示表中的所有记录。查询如下。

mysql> select *from StudentInformation;

以下是输出。

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 1         | John        | 23         |
| 2         | Adam        | 24         |
| 3         | Bob         | 21         |
| 4         | Carol       | 20         |
| 5         | Mike        | 25         |
+-----------+-------------+------------+
5 rows in set (0.00 sec)

以下是将查询结果设置为变量的查询。

mysql> select StudentAge into @yourAge from StudentInformation where StudentName='Adam';
Query OK, 1 row affected (0.03 sec)

检查变量 @yourAge 中存储的内容。查询如下。

mysql> select @yourAge;

以下是显示学生 Adam 年龄的输出。

+----------+
| @yourAge |
+----------+
| 24       |
+----------+
1 row in set (0.00 sec)

相关文章