问题描述
假设你有以下表格和数据
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);
关联表将文章与与之关联的最高级别标签链接起来。遍历标签并生成完整链的最佳方法是什么?
例如对于上面的数据我们应该看到
我已经尝试使用 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