Oracle sql - 从链接表生成完整的分层链

问题描述

假设你有以下表格和数据

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,'another parent');
insert into associations values (1,102);
insert into associations values (2,101);
insert into associations values (3,103);

关联表将文章与与之关联的最高级别标签链接起来。遍历标签生成完整链的最佳方法是什么?

例如对于上面的数据我们应该看到

文章名称 标签名称
item 1
item 1 child
item 1 孙子
项目 2
项目 2 child
item 3 一个父级

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

解决方法

您可以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 | TAG_NAME      
:----------- | :-------------
item 1       | grandchild    
item 1       | child         
item 1       | parent        
item 2       | child         
item 2       | parent        
item 3       | another parent

dbfiddle here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...