如何使用 MySQL 将查询结果存储在变量中?


要使用 MySQL 将查询结果存储在变量中,请使用 SET 命令。语法如下:−

SET @anyVariableName = ( yourQuery);

要理解上述概念,让我们创建一个表。以下是要创建表的查询:−

mysql> create table QueryResultDemo
   −> (
   −> Price int
   −> );
Query OK, 0 rows affected (0.59 sec)

现在让我们将一些记录插入到表中。以下是要插入记录的查询:−

mysql> insert into QueryResultDemo values(100);
Query OK, 1 row affected (0.17 sec)

mysql> insert into QueryResultDemo values(20);
Query OK, 1 row affected (0.13 sec)

mysql> insert into QueryResultDemo values(200);
Query OK, 1 row affected (0.10 sec)

mysql> insert into QueryResultDemo values(80);
Query OK, 1 row affected (0.15 sec)

利用选择语句从表中显示所有记录。以下是要显示所有记录的查询:−

mysql> select *from QueryResultDemo;

以下是输出:−

+-------+
| Price |
+-------+
|   100 |
|    20 |
|   200 |
|    80 |
+-------+
4 rows in set (0.00 sec)

现在,借助 SET 命令,可以在变量中设置查询结果。查询如下。

mysql> Set @TotalPrice = (select sum(Price) from QueryResultDemo);
Query OK, 0 rows affected (0.00 sec)

使用 SELECT 语句检查“TotalPrice”变量中存储的值:−

mysql> select @TotalPrice;

以下是输出:−

+-------------+
| @TotalPrice |
+-------------+
|         400 |
+-------------+
1 row in set (0.00 sec)

更新时间:2019 年 7 月 30 日

8K+ 浏览

开启你的 职业生涯

通过完成课程获取认证

开始
广告
© . All rights reserved.