如何将 MySQL 查询结果分配给一个变量?
使用 @anyVariableName 将查询结果分配给变量。我们首先创建一个表 -
mysql> create table DemoTable1864 ( Id int, FirstName varchar(20), LastName varchar(20) ); Query OK, 0 rows affected (0.00 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable1864 values(101,'Chris','Brown'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1864 values(102,'David','Miller'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1864 values(103,'Adam','Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1864 values(104,'John','Doe'); Query OK, 1 row affected (0.00 sec)
使用选择语句显示表中的所有记录 -
mysql> select * from DemoTable1864;
这将产生以下输出 -
+------+-----------+----------+ | Id | FirstName | LastName | +------+-----------+----------+ | 101 | Chris | Brown | | 102 | David | Miller | | 103 | Adam | Smith | | 104 | John | Doe | +------+-----------+----------+ 4 rows in set (0.00 sec)
以下是将查询结果分配给变量的查询 -
mysql> select @fName:=FirstName,@lName:=LastName from DemoTable1864 where Id=103;
这将产生以下输出 -
+-------------------+------------------+ | @fName:=FirstName | @lName:=LastName | +-------------------+------------------+ | Adam | Smith | +-------------------+------------------+ 1 row in set (0.00 sec)
广告