English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to execute a recursive SELECT query in MySQL?

For recursive selection, let's look at an example. First, we will create a table. The CREATE command is used to create a table.

mysql> CREATE table tblSelectDemo
   - > (
   - > id int,
   - > name varchar(100)
   - > );

Now, we will insert records into the 'tblSelectDemo' table.

mysql> insert into tblSelectDemo values(1,'John');
mysql> insert into tblSelectDemo values(2,'Carol');
mysql> insert into tblSelectDemo values(3,'Smith');
mysql> insert into tblSelectDemo values(4,'David');
mysql> insert into tblSelectDemo values(5,'Bob');

Display all records.

mysql> SELECT *from tblSelectDemo;

This is the output.

+------+-------+
| id | name |
+------+-------+
|    1 | John |
|    2 | Carol |
|    3 | Smith |
|    4 | David |
|    5 | Bob |
+------+-------+
6 rows in set (0.00 sec)

Here is the syntax for recursive SELECT.

mysql> SELECT var1.id as id, @sessionName := var1.Name as Name of Student
   - > from (select * from tblSelectDemo order by id desc) var1
   - > join
   - > select @sessionName := 4)tmp
   - > where var1.id = @sessionName;

This is the output.

+------+----------------+
| id | Name of Student |
+------+----------------+
|    4 | David |
+------+----------------+
1 row in set (0.00 sec)