使用级别路径从 table 生成父子层次结构

Generate a parent-child hierarchy from table with levels paths

我设法在这样的 table 中转换了一些不可读的数据。 SQL table 表示多父平面层次结构。问题是,我怎样才能生成一个普通的参差不齐的 sql parent-child 层次结构:ID | Element | Parent 基于级别和下面附加的结构?

您可以创建一个具有层次结构和自动递增 ID 的新 table,如下所示:

create table hierarchy (
  id int not null identity (1,1) primary key,
  element varchar(100),
  parent int
);

然后你会首先向它添加 1 级元素,因为它们没有父级:

insert into hierarchy (element, parent)
  select     distinct f.level1, null
  from       flat f;

因为您现在已经为这些元素生成了 id 值,您可以添加下一个级别,如下所示:

insert into hierarchy (element, parent)
  select     distinct f.level2, h1.id
  from       hierarchy h1
  inner join flat f
          on f.level1 = h1.element
  where      h1.parent is null;

这个模式你可以重复到下一个级别:

insert into hierarchy (element, parent)
  select     distinct f.level3, h2.id
  from       hierarchy h1
  inner join hierarchy h2
          on h2.parent = h1.id
  inner join flat f
          on f.level1 = h1.element
         and f.level2 = h2.element
  where      h1.parent is null;

insert into hierarchy (element, parent)
  select     distinct f.level4, h3.id
  from       hierarchy h1
  inner join hierarchy h2
          on h2.parent = h1.id
  inner join hierarchy h3
          on h3.parent = h2.id
  inner join flat f
          on f.level1 = h1.element
         and f.level2 = h2.element
         and f.level3 = h3.element
  where      h1.parent is null;

insert into hierarchy (element, parent)
  select     distinct f.level5, h3.id
  from       hierarchy h1
  inner join hierarchy h2
          on h2.parent = h1.id
  inner join hierarchy h3
          on h3.parent = h2.id
  inner join hierarchy h4
          on h4.parent = h3.id
  inner join flat f
          on f.level1 = h1.element
         and f.level2 = h2.element
         and f.level3 = h3.element
         and f.level4 = h4.element
  where      h1.parent is null;

insert into hierarchy (element, parent)
  select     distinct f.level6, h3.id
  from       hierarchy h1
  inner join hierarchy h2
          on h2.parent = h1.id
  inner join hierarchy h3
          on h3.parent = h2.id
  inner join hierarchy h4
          on h4.parent = h3.id
  inner join hierarchy h5
          on h5.parent = h4.id
  inner join flat f
          on f.level1 = h1.element
         and f.level2 = h2.element
         and f.level3 = h3.element
         and f.level4 = h4.element
         and f.level5 = h5.element
  where      h1.parent is null;

...等等,根据需要进入各个级别。