

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
- Related Questions & Answers
- How to use alias in MySQL select query?
- MySQL query to select too many rows?
- MySQL query to select date from timestamp?
- MySQL query to select top 10 records?
- MySQL query to select bottom n records
- MySQL query to select multiple rows effectively?
- How to order and select query with conditions in MySQL?
- MySQL select query with multiple WHERE?
- Select first word in a MySQL query?
- Select query with regular expression in MySQL
- Insert with a Select query in MySQL
- How to select part of a Timestamp in a MySQL Query?
- MySQL query to select distinct order by id
- MySQL query to select top n rows efficiently?
- MySQL query to select closest date from today?
Advertisements