mysql 自顶向下递归查询 使用next字段查子集 单链表查询

现在有一个需求,
给定的表结构支持单链表数据的存储,每一行有一个next字段指向下一个节点,在只知道根节点id的情况下查询出该链表的所有数据

表结构

create table node
(
    id   int PRIMARY KEY AUTO_INCREMENT,
    name varchar(20),
    next int
);

该表存储的是多个单链表的数据,已知某个链表的rootId,需要根据rootId递归查询出整个链表的所有节点

初始化数据,插入两条链表的数据


insert into node VALUE (1, '1', 2);
insert into node VALUE (2, '2', 3);
insert into node VALUE (3, '3', 4);
insert into node VALUE (4, '4', 5);
insert into node VALUE (5, '5', 6);
insert into node VALUE (6, '6', 7);
insert into node VALUE (7, '7', 8);
insert into node VALUE (8, '8', null);

insert into node VALUE (111, '111', 222);
insert into node VALUE (222, '222', 333);
insert into node VALUE (333, '333', 444);
insert into node VALUE (444, '444', 555);
insert into node VALUE (555, '555', null);

查询语句如下,查询其中头结点id为111的链表

SELECT id, name, next
FROM node
         INNER JOIN (
    SELECT 111 AS a # 111为头节点Id
    UNION
    SELECT @next_id AS a
    FROM node,
         (SELECT @next_id := 111) n # 111为头节点Id
    WHERE id = @next_id
        AND @next_id := next
    # 其他条件
) ids
ON node.id = ids.a;

查询结果

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值