如何利用 MySQL 中查詢的結果設定使用者變數?


要利用 MySQL 中查詢的結果設定使用者變數,你需要將變數移動到分配中。

為了理解上述概念,讓我們先建立一個表。建立表的查詢如下 −

mysql> create table UserVariable
   -> (
   -> Id int,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.53 sec)

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

mysql> insert into UserVariable values(101,'John');
Query OK, 1 row affected (0.17 sec)

mysql> insert into UserVariable values(200,'Tom');
Query OK, 1 row affected (0.18 sec)

mysql> insert into UserVariable values(500,'Carol');
Query OK, 1 row affected (0.13 sec)

使用選擇命令顯示錶中的所有記錄。查詢如下 −

mysql> select *from UserVariable;

輸出

+------+-------+
| Id   | Name  |
+------+-------+
|  101 | John  |
|  200 | Tom   |
|  500 | Carol |
+------+-------+
3 rows in set (0.00 sec)

編寫一個使用使用者變數的查詢,顯示具有最大 ID 的記錄。首先,我將建立一個變數並透過從上述表中選擇最大 ID 來初始化此變數。查詢如下 −

mysql> set @Maxid=(select MAX(Id) from UserVariable);
Query OK, 0 rows affected (0.00 sec)

然後,建立一個僅具有該特定最大 ID 的名稱的另一個變數。查詢如下 −

mysql> set @Name=(select Name from UserVariable where Id=@Maxid);
Query OK, 0 rows affected (0.00 sec)

現在你可以檢查變數 Name 中存在什麼值。查詢如下 −

mysql> select @Name;

以下是顯示具有最高 Id 的名稱的輸出 −

+-------+
| @Name |
+-------+
| Carol |
+-------+
1 row in set (0.00 sec)

更新於:30-Jul-2019

943 次瀏覽

開啟你的職業生涯

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.