仮定:
区分が主キーです。
行レベルの説明がnullの場合、親行を参照してください。 Parent行にnullの説明がある場合は、親の親を参照してください。他の言葉では、祖先の最初のnullでない記述を使用します。
行レベルの説明がnull、およびNO祖先が非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
出力は、カテゴリIDから最終的な説明へのマッピングです。
再利用の観点からは、私は上記のことを考えます。
使用しているSQLのブランドは? – Talljoe
おそらくvarchar(MAX)の構文からSQLServerのように見えますか? – Plasmer
MsSql、申し訳ありませんが、テーブルがどのように見えるのか疑似コードでした。 誰かがこれを達成するために関数を使用できると思いますか?私は「もの」のものが好きです。 MySqlには「with」がありますか? –