Computer >> Computer tutorials >  >> Programming >> MySQL

How to do recursive SELECT query in MySQL?


For recursive select, let us see 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)
   - > );
Query OK, 0 rows affected (0.61 sec)

Now, we will insert records in the table “tblSelectDemo”.

mysql> insert into tblSelectDemo values(1,'John');
Query OK, 1 row affected (0.10 sec)

mysql> insert into tblSelectDemo values(2,'Carol');
Query OK, 1 row affected (0.09 sec)

mysql> insert into tblSelectDemo values(3,'Smith');
Query OK, 1 row affected (0.17 sec)

mysql> insert into tblSelectDemo values(4,'David');
Query OK, 1 row affected (0.15 sec)

mysql> insert into tblSelectDemo values(5,'Bob');
Query OK, 1 row affected (0.18 sec)

To display all records.

mysql> SELECT *from tblSelectDemo;

Here is the output.

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

The following is the syntax for recursive SELECT.

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

Here is the output.

+------+----------------+
| id   | NameofStudent  |
+------+----------------+
|    4 | David          |
+------+----------------+
1 row in set (0.00 sec)