MySQL 臨時變數分配?
您可以使用 SET 命令進行臨時變數分配。
語法如下
SET @anyVariableName=(SELECT yourColumnName FROM yourTableName WHERE yourCondition);
為了理解上述語法,讓我們建立一個表。建立表的查詢如下
mysql> create table tempVariableAssignment -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20), -> Age int -> ); Query OK, 0 rows affected (0.59 sec)
現在使用 insert 命令在表中插入一些記錄
mysql> insert into tempVariableAssignment(Name,Age) values('John',25);
Query OK, 1 row affected (0.14 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('Carol',26);
Query OK, 1 row affected (0.17 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('Sam',28);
Query OK, 1 row affected (0.13 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('David',19);
Query OK, 1 row affected (0.19 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('Bob',23);
Query OK, 1 row affected (0.19 sec)使用 select 語句顯示錶中的所有記錄。
查詢如下
mysql> select *from tempVariableAssignment;
以下是輸出
+----+-------+------+ | Id | Name Age | +----+-------+------+ | 1 | John | 25 | | 2 | Carol | 26 | | 3 | Sam | 28 | | 4 | David | 19 | | 5 | Bob | 23 | +----+-------+------+ 5 rows in set (0.00 sec)
以下是 MySQL 臨時變數分配的查詢
mysql> set @findAge=(select Age from tempVariableAssignment where Id=4); Query OK, 0 rows affected (0.02 sec)
顯示變數 @findAge 的值。
查詢如下
mysql> select @findAge;
以下是輸出
+----------+ | @findAge | +----------+ | 19 | +----------+ 1 row in set (0.01 sec)
這裡有一個備用查詢
mysql> select Age INTO @anotherAge -> from tempVariableAssignment where Id=4; Query OK, 1 row affected (0.00 sec)
顯示變數 @anotherAge 的值。
查詢如下
mysql> select @anotherAge;
以下是輸出
+-------------+ | @anotherAge | +-------------+ | 19 | +-------------+ 1 row in set (0.00 sec)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP