SQL每日一题(2020-06-05)

2020-06-08  本文已影响0人  扎西的德勒

题目:

有一张表T,里面的数据如下:

image

希望得到如下结果

image

该如何写这个查询?

参考答案:

数据库版本: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;

附:
题目来源:https://mp.weixin.qq.com/s/DmIkopgSmL3a_y3xaW5YBA

上一篇 下一篇

猜你喜欢

热点阅读