您可以使用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
-> );
现在使用插入命令在表中插入一些记录mysql> insert into tempVariableAssignment(Name,Age) values('John',25);
mysql> insert into tempVariableAssignment(Name,Age) values('Carol',26);
mysql> insert into tempVariableAssignment(Name,Age) values('Sam',28);
mysql> insert into tempVariableAssignment(Name,Age) values('David',19);
mysql> insert into tempVariableAssignment(Name,Age) values('Bob',23);
使用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);
显示变量@findAge的值。
查询如下mysql> select @findAge;
以下是输出+----------+
| @findAge |
+----------+
| 19 |
+----------+
1 row in set (0.01 sec)
这是一个替代查询mysql> select Age INTO @anotherAge
-> from tempVariableAssignment where Id=4;
显示变量@anotherAge的值。
查询如下mysql> select @anotherAge;
以下是输出+-------------+
| @anotherAge |
+-------------+
| 19 |
+-------------+
1 row in set (0.00 sec)