SQL查询找出父任务和子任务

问题描述

我有一个满足此类信息的表格。 在该条目ID中,如果没有父任务,并且ind_id包含一个值,则它提到了父任务的entry_id。该ID用作唯一ID,并且ind_id为'0'。

工作流程

a-- no child
b-- child is c
  c-- parent is b
d-- child f
  f-- parent d,child e
    e-- parent f child g 
    o-- parent f child g
      g-- parent e no child
  .....more sub task may come ......
h-- no child
  i-- parent h 
j-- no child
k-- no child

下表示例

entry_id | task            | ind_id | date
------------------------------------------------
1001     | example_1       | 0      | 22-08-2020
1000     | example_1       | 0      | 22-08-2020
1012     | example_3       | 1000   | 22-08-2020
1013     | example_4       | 1000   | 22-08-2020
1004     | example_1_14    | 0      | 22-08-2020
1006     | example_2_4     | 1004   | 22-08-2020
1007     | example_8_4     | 1006   | 22-08-2020
1010     | example_4_1     | 0      | 22-08-2020

我想要这样的数据。

entry_id | task            | ind_id |parent_task_name | child_task_name      | date
---------------------------------------------------------------------------------------
1001     | example_1       | 0      |null             |null                  | 22-08-2020
1000     | example_1       | 0      |null             |example_3,example_4  | 22-08-2020
1012     | example_3       | 1000   |example_1        |null                  | 22-08-2020
1013     | example_4       | 1000   |example_1        |null                  | 22-08-2020
1004     | example_1_14    | 0      |null             |example_2_4           | 22-08-2020
1006     | example_2_4     | 1004   |example_1_14     |example_8_4           | 22-08-2020
1007     | example_8_4     | 1006   |example_2_4      |null                  | 22-08-2020
1010     | example_4_1     | 0      |null             |null                  | 22-08-2020

有人会帮助我找到解决方案的吗?

解决方法

您可以使用递归CTE为每个条目定义路径,然后按以下顺序进行排序:

with recursive cte as (
      select entry_id,concat(entry_id) as path
      from t
      where ind_id = 0
      union all
      select t.entry_id,concat_ws('>',path,t.entry_id)
      from cte join
           t
           on t.ind_id = cte.entry_id
     )
select t.*
from t join
     cte
     on t.entry_id = cte.entry_id
order by cte.path;

Here是db 小提琴。

重要说明:这适用于您的示例数据,因为所有条目ID的长度均相同。如果不是,则将其格式化或填充为固定长度。这样,对字符串进行排序即可产生您期望的结果。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...