MySQL 临时变量赋值?
mysqlmysqli database
可以使用 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)
现在使用插入命令在表中插入一些记录
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)