
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
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 Articles
- How to use alias in MySQL select query?
- How to order and select query with conditions in MySQL?
- How to select part of a Timestamp in a MySQL 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 write a MySQL query to select first 10 records?
- How to use prepared statement for select query in Java with MySQL?
- How to get a specific column record from SELECT query in MySQL?
- Select first word in a MySQL query?
- Select query with regular expression in MySQL
- Insert with a Select query in MySQL
- MySQL query to select closest date from today?

Advertisements