在 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
-> );
Query OK, 0 rows affected (0.62 sec)

使用插入命令在表中插入一些記錄。查詢如下。

mysql> insert into StudentInformation values(1,'John',23);
Query OK, 1 row affected (0.21 sec)

mysql> insert into StudentInformation values(2,'Adam',24);
Query OK, 1 row affected (0.17 sec)

mysql> insert into StudentInformation values(3,'Bob',21);
Query OK, 1 row affected (0.20 sec)

mysql> insert into StudentInformation values(4,'Carol',20);
Query OK, 1 row affected (0.17 sec)

mysql> insert into StudentInformation values(5,'Mike',25);
Query OK, 1 row affected (0.13 sec)

使用 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';
Query OK, 1 row affected (0.03 sec)

檢查變數 @yourAge 中儲存的內容。查詢如下。

mysql> select @yourAge;

以下是在輸出中顯示 Adam 學生的年齡。

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

更新於: 29-6 月 -2020

344 次瀏覽

開啟你的職業生涯

完成課程即可獲得證書

開始
廣告
© . All rights reserved.