如何使用MySQL将查询结果存储到变量中?
要使用MySQL将查询结果存储到变量中,请使用SET命令。语法如下:-
SET @任意变量名 = (您的查询);
为了理解上述概念,让我们创建一个表。以下是创建表的查询:-
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)
使用select语句显示表中的所有记录。显示所有记录的查询如下:-
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)
阅读更多:MySQL 教程
极客教程