廣度優先,從子節點找到到根路徑的sql

2022-02-07 04:37:58 字數 1811 閱讀 3953

/*

註解:以前遇到過乙個同事,在處理樹的時候,在sql語句裡面用遞迴,造成效能非常低下。

在遇到sql處理樹的時候,可以採用以下方法,用迴圈來解決。

主要思路:

找到cateogry的parent插入臨時表,在臨時表裡做遍歷,每到一條記錄,都做乙個操作:將它的parent select出來,插入臨時表,最後,將臨時表join cateogry表。

*/set ansi_nulls on

set quoted_identifier on

goalter procedure [dbo].[proc_getcategorypath]

@categoryid uniqueidentifier

asif exists (select * from dbo.sysobjects where id=object_id(n'#_name') and objectproperty(id, n'isusertable')=1)

drop table #_name

/*建乙個臨時表*/

create table [dbo].[#_name] (

[id] [bigint] identity (1, 1) not null,

[parentcategoryid] uniqueidentifier null ,

[categoryid] uniqueidentifier null ,

[ordernum] [int] null

) on [primary]

/*do insert*/

insert into #_name

select

[category].[parentcategoryid],

[category].[id] as cateogryid,

[category].[ordernum]

from

[category]

where

[category].[id] = @categoryid

order by [category].[ordernum]

declare @id bigint

set @id = 1

declare @parent uniqueidentifier

set @parent = (select top 1 [parentcategoryid] from #_name where id = @id)

while (@parent is not null and @parent <> '00000000-0000-0000-0000-000000000000')

begin

insert into #_name

select

[category].[parentcategoryid],

[category].[id] as categoryid,

[category].[ordernum]

from

[category]

where

[category].[id] = @parent

order by [category].[ordernum]

set @id = @id + 1

set @parent = (select top 1 [parentcategoryid] from #_name where id = @id)

end/*end do insert*/

select [category].*

from #_name

join category on [#_name].[categoryid] = [category].[id]

深度優先 廣度優先

父類定義 class people def init self,name,age,weight self.name name self.age age self.weight weight defspeak self print s 說 我 d 歲。self.name,self.age 單繼承示例 ...

廣度優先遍歷

廣度優先遍歷 breadth first search 類似於對樹的層序遍歷 遍歷規則為 首先訪問初始點vi,並將其標記為已訪問過,接著訪問vi的所有未被訪問過的鄰接點,其訪問次序可以任意,假定依次為vi1,vi2,vit,並均標記為已訪問過,然後在按照vi1,vi2,vit的次序,訪問每乙個頂點的...

廣度優先搜尋

include include include include using namespace std struct node 圖頂點結構定義 typedef struct node graph 圖形的結構新型態 struct node head 9 圖形頂點陣列 int visited 9 遍歷標...