sql樹結構
A. 關於sql查詢樹結構數據的語句
方法1:
是否可以有代表層次的欄位,若有,直接根據層次欄位查詢;
方法2:
是否存在以下假設:
非父級的dept_uid的 不可能 在 parent_uid 中出現。
如果假設成立,在查出的所有dept_uid中去掉,所有在在 parent_uid 中出現id,
剩下的就是你要的了。
B. 怎麼往資料庫里插入一個樹形結構的表,並且用一句SQL語句將其遍歷出來
ID Value PID
0 根節點 null
1 節點1 0
2 節點2 0
3 節點3 1
..........
然後查詢出來 再形成樹就可以了
C. sql server怎麼對樹形結構表的節點進行拼接
DECLARE @temp nvarchar(MAX)='',@pid bigint=3;
WHILE @pid<>0 BEGIN IF @temp=''
SELECT @temp=TypeName,@pid=ParentId
FROM [dbo].[Test]
WHERE Id=@pid;
ELSE
SELECT @temp=(TypeName+'->'+@temp),@pid=ParentId
FROM [dbo].[Test]
WHERE Id=@pid;
END;
SELECT @temp AS TypeName;
D. sql server 2005資料庫中怎樣建立樹形結構表
樹形結構表關鍵就是要有上一級的關聯欄位:
parentid
ID
.......
這樣自然而然的就成為了樹形結構表了。
E. 在MySql下,怎麼用SQL語句遍歷一個樹結構
f exists (select * from dbo.sysobjects where id = object_id(N'[tb]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [tb]
GO
--示例數據
create table [tb]([id] int identity(1,1),[pid] int,name varchar(20))
insert [tb] select 0,'中國'
union all select 0,'美國'
union all select 0,'加拿大'
union all select 1,'北京'
union all select 1,'上海'
union all select 1,'江蘇'
union all select 6,'蘇州'
union all select 7,'常熟'
union all select 6,'南京'
union all select 6,'無錫'
union all select 2,'紐約'
union all select 2,'舊金山'
go
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_id]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_id]
GO
/*--樹形數據處理
級別及排序欄位
--鄒建 2003-12(引用請保留此信息)--*/
/*--調用示例
--調用函數實現分級顯示
select replicate('-',b.[level]*4)+a.name
from [tb] a,f_id()b
where a.[id]=b.[id]
order by b.sid
--*/
create function f_id()
returns @re table([id] int,[level] int,sid varchar(8000))
as
begin
declare @l int
set @l=0
insert @re select [id],@l,right(10000+[id],4)
from [tb] where [pid]=0
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.[id],@l,b.sid+right(10000+a.[id],4)
from [tb] a,@re b
where a.[pid]=b.[id] and b.[level]=@l-1
end
return
end
go
--調用函數實現分級顯示
select replicate('-',b.[level]*4)+a.name
from [tb] a,f_id()b
where a.[id]=b.[id]
order by b.sid
go
--刪除測試
drop table [tb]
drop function f_id
go
/*--結果
中國
----北京
----上海
----江蘇
--------蘇州
------------常熟
--------南京
--------無錫
美國
----紐約
----舊金山
加拿大
--*/
F. sql里樹形結構分組排序
createtableT1(thisvarchar(10),parentvarchar(10))
insertintoT1(this,parent)
values('id1',null)
,('id2',null)
,('id3','id1')
,('id4','id2')
,('id5','id3')
,('id6','id3')
,('id7','id4')
,('id8','id7')
--sqlserver的cte功能
withtree(this,parent,root,depth)as(
selectthis,parent,thisasroot,
unionall
selecta.this,a.parent,b.root,b.depth+1asdepthfromT1a,treebwherea.parent=b.this
)
selectthis,parent,root,depth
fromtree
orderbyroot,depth,this