Set user variable from result of query in MySQL?

MySQLMySQLi Database

To set user variable from result of query in MySQL, you need to move that variable into the assignment.

To understand the above concept, let us first create a table. The query to create a table is as follows −

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

Insert some records in the table using insert command. The query is as follows −

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)

Display all records from the table using select command. The query is as follows −

mysql> select *from UserVariable;

Output

+------+-------+
| Id   | Name  |
+------+-------+
|  101 | John  |
|  200 | Tom   |
|  500 | Carol |
+------+-------+
3 rows in set (0.00 sec)

Write a query with a user variable that display the records with maximum id. First, I am going to create a variable and initialize this variable by selecting maximum id from the above table. The query is as follows −

mysql> set @Maxid=(select MAX(Id) from UserVariable);
Query OK, 0 rows affected (0.00 sec)

After that, create another variable which has only name with that particular maximum id. The query is as follows −

mysql> set @Name=(select Name from UserVariable where Id=@Maxid);
Query OK, 0 rows affected (0.00 sec)

Now you can check what value is present in variable Name. The query is as follows −

mysql> select @Name;

The following is the output that displays the name with the highest Id −

+-------+
| @Name |
+-------+
| Carol |
+-------+
1 row in set (0.00 sec)
raja
Published on 10-Jan-2019 16:20:39
Advertisements