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

您可以使用 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
-> );

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

mysql> insert into StudentInformation values(1,'John',23);

mysql> insert into StudentInformation values(2,'Adam',24);

mysql> insert into StudentInformation values(3,'Bob',21);

mysql> insert into StudentInformation values(4,'Carol',20);

mysql> insert into StudentInformation values(5,'Mike',25);

使用 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';

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

mysql> select @yourAge;

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

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