【问题标题】:Oracle sql - Generate full hierarchical chain from link tableOracle sql - 从链接表生成完整的层次链
【发布时间】:2021-04-28 15:37:46
【问题描述】:

假设你有以下表格和数据

create table articles (article_id number, name varchar2(30));
create table tags (tag_id number, parent_tag_id number, name varchar2(30));
create table associations (article_id number, tag_id number);
insert into articles values (1, 'item 1');
insert into articles values (2, 'item 2');
insert into articles values (3, 'item 3');
insert into tags values (100, null, 'parent');
insert into tags values (101, 100, 'child');
insert into tags values (102, 101, 'grandchild');
insert into tags values (103, null, 'another parent');
insert into associations values (1, 102);
insert into associations values (2, 101);
insert into associations values (3, 103);

关联表链接具有与其关联的最高级别标签的文章。遍历标签并生成完整链的最高效方式是什么?

例如对于上述数据,我们应该看到

Article Name Tag Name
item 1 parent
item 1 child
item 1 grandchild
item 2 parent
item 2 child
item 3 another parent

我尝试使用connect by prior 来生成标签和父标签之间的关系,但是我很难将三个表链接在一起并保留文章名称(我想知道使用connect_by_root 来保留名称)

【问题讨论】:

    标签: sql oracle oracle19c oracle18c hierarchical-query


    【解决方案1】:

    你可以CROSS APPLY一个相关的层次查询:

    SELECT r.name AS article_name,
           t.name AS tag_name
    FROM   articles r
           INNER JOIN associations a
           ON ( r.article_id = a.article_id )
           CROSS APPLY(
             SELECT name
             FROM   tags t
             START WITH t.tag_id = a.tag_id
             CONNECT BY PRIOR parent_tag_id = tag_id
           ) t
    

    对于您的样本数据,输出:

    ARTICLE_NAME |标签名称 :----------- | :------------- 项目 1 |孙子 项目 1 |孩子 项目 1 |父母 项目 2 |孩子 项目 2 |父母 项目 3 |另一位家长

    db小提琴here

    【讨论】:

    • 完美。谢谢
    猜你喜欢
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 2017-06-23
    相关资源
    最近更新 更多