가정 :
카테고리 ID는 기본 키입니다.
행 수준의 설명이 null 인 경우 상위 행을 살펴보십시오. 부모 행에 null 설명이 있으면 부모의 부모를 봅니다. 다른 말로하면 조상에 대한 첫 번째 null이 아닌 설명을 사용합니다. 로우 레벨 정보가 널 및 조상 비 널 묘사 없으면
은 전반적인 설명
설정 예에 나타난 테스트 데이터 널.
create table #SO (CategoryID int primary key
, ParentCategoryID int Null
, Name varchar(255) not null
, Description varchar(MAX) Null
)
insert into #SO (CategoryID, ParentCategoryID, Name, Description)
values (1, null, 'Top 1', 'Top 1 Description')
, (2, null, 'Top 2', 'Top 2 Description')
, (3, null, 'Top 3', null)
, (11, 1, 'Child 11', 'Child 11 Description')
, (12, 1, 'Child 12', null)
, (21, 2, 'Child 21', null)
, (211, 21, 'Child 211', null)
, (2111, 211, 'Child 2111', null)
, (2112, 211, 'Child 2112', 'Child 2112 Description')
, (31, 3, 'Child 31', 'Child 31 Description')
, (32, 3, 'Child 32', null)
재귀 CTE를 사용합니다. 트리는 위쪽으로 걸어갔습니다.우리는 모든 행부터 시작한 다음 나무 꼭대기에서 시작하여 아래로 작업하는 일반적인 트리 조작 대신에 필요에 따라 부모를 봅니다.
; with Description (BaseCategoryId
, CurrentParentCategoryId
, CurrentDescription
, CurrentLevel)
as
(-- Anchor -- Start with all rows in the table.
select CategoryId as BaseCategoryId
, ParentCategoryId as CurrentParentCategoryId
, Description as CurrentDescription
, 0 as CurrentLevel
from #SO -- Recursive -- We are walking up the tree from all nodes,
-- We only continue up the tree when we do not have a description yet.
union all
select D.BaseCategoryId
, so.ParentCategoryId
, so.Description
, D.CurrentLevel + 1
from #SO so
inner join Description D
on D.CurrentParentCategoryId = so.CategoryId
and D.CurrentDescription is null)
select DL.BaseCategoryId as CategoryId
, DL.CurrentDescription as UltimateDescription
-- Now self outer join with the CTE every step of the walk
-- for each BaseCategoryId, and then filter all but the top
-- level. (Level is measured as distance from base.)
from Description as DL
left outer join Description as DR
on DL.BaseCategoryId = DR.BaseCategoryId
and DL.CurrentLevel < DR.CurrentLevel
where DR.BaseCategoryId is null
order by DL.BaseCategoryId
출력은 CategoryId에서 최종 설명까지의 매핑입니다.
재사용 관점에서 볼 때 위와 같은 것을 볼 수 있습니다.
어떤 SQL 브랜드를 사용하고 있습니까? – Talljoe
아마도 varchar (MAX) 구문에서 SQLServer처럼 보입니까? – Plasmer
MsSql, 미안 그 표가 어떻게 생겼는지에 대한 의사 코드 일뿐입니다. 누구나이 기능을 사용하기 위해 함수를 사용할 수 있다고 생각합니까? 나는 '함께'물건을 좋아한다. MySql에 '함께'있습니까? –