如何在 MySQL 中执行递归 SELECT 查询?
mysqlmysqli database
对于递归选择,让我们看一个例子。首先,我们将创建一个表。CREATE 命令用于创建表。
mysql> CREATE table tblSelectDemo - > ( - > id int, - > name varchar(100) - > ); Query OK, 0 rows affected (0.61 sec)
现在,我们将在表"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)
显示所有记录。
mysql> SELECT *from tblSelectDemo;
这是输出。
+------+-------+ | id | name | +------+-------+ | 1 | John | | 2 | Carol | | 3 | Smith | | 4 | David | | 5 | Bob | +------+-------+ 6 rows in set (0.00 sec)
以下是递归 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;
这是输出。
+------+----------------+ | id | NameofStudent | +------+----------------+ | 4 | David | +------+----------------+ 1 row in set (0.00 sec)