如何使用 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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP