如何使用 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.