题目:
有一张表T,里面的数据如下:
希望得到如下结果
该如何写这个查询?
参考答案:
数据库版本:Server version: 8.0.20 MySQL Community Server - GPL
建表语句
create table dailytest_20200605(
id int,
pid int
);
数据准备
insert into dailytest_20200605 values(1,0),(2,1),(3,2),(4,3);
查询逻辑
select c.id,
c.pid,
group_concat(c.bid order by c.id SEPARATOR '>') as path
from (select a.id,
a.pid,
b.id as bid
from dailytest_20200605 a
left join dailytest_20200605 b
on a.id >= b.id
order by a.id) c
group by c.id, c.pid;
网友评论