在 MySQL 中根据查询结果设置用户变量?

mysqlmysqli database

要在 MySQL 中根据查询结果设置用户变量,您需要将该变量移入赋值中。

为了理解上述概念,让我们首先创建一个表。创建表的查询如下 −

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

使用 insert 命令在表中插入一些记录。 查询语句如下 −

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)

使用 select 命令显示表中的所有记录。查询如下 −

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)

现在您可以检查变量名称中存在的值。查询如下 −

mysql> select @Name;

以下是显示 Id 最高的名称的输出 −

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

相关文章