一个查询
表zone:
id name pid
1 黑龙江省 0
2 辽宁省 0
4 哈尔滨 1
5 北京 0
6 沈阳 2
7 长沙 8
8 湖南 0
这是一个省市表,pid字段记录市的上级省
我想通过一个查询把他们关联起来就像下面这样:
黑龙江省
哈尔滨
辽宁省
沈阳
湖南
长沙
北京
如何查询?
[解决办法]
似乎要用递归吧...
[解决办法]
--建立測試環境
Create Table zone
(idInt,
nameNvarchar(10),
pidInt)
--插入數據
Insert zone Select 1, N '黑龙江省 ', 0
Union All Select 2, N '辽宁省 ', 0
Union All Select 4, N '哈尔滨 ', 1
Union All Select 5, N '北京 ', 0
Union All Select 6, N '沈阳 ', 2
Union All Select 7, N '长沙 ', 8
Union All Select 8, N '湖南 ', 0
GO
--建立存儲過程
Create Procedure SP_TEST
As
Begin
--深度排序显示处理
--生成每个节点的编码累计
Declare @Level Int
Set @Level=0
Select id, id As pid, @Level As Level, ', ' + Rtrim(id) As Sort Into #T
From zone
Where pid = 0
While @@ROWCOUNT> 0
Begin
Set @Level = @Level + 1
Insert #T Select A.id, B.pid, @Level, B.Sort+ ', ' + Rtrim(A.id)
From zone A, #T B
Where A.pid = B.id
And B.Level = @Level - 1
End
--显示结果
Select SPACE(B.Level *2) + Rtrim(A.Name) As Name
From zone A, #T B
Where A.id = B.id
Order By B.pid, B.Sort
--刪除臨時表
Drop Table #T
End
GO
--測試
EXEC SP_TEST
GO
--刪除測試環境
Drop Table zone
Drop Procedure SP_TEST
--結果
/*
Name
黑龙江省
哈尔滨
辽宁省
沈阳
北京
湖南
长沙
*/
[解决办法]
鱼sql四星来了.学习了。
[解决办法]
...
MySQL就沒辦法了,不會。 :)
[解决办法]
MARK
[解决办法]
我就用笨办法 。。。。用 嵌套循环也可以达到效果
[解决办法]
建两张表呀
[解决办法]
create database TestDataBase
Create Table zone
(idInt,
nameNvarchar(10),
pidInt)
--插入數據
Insert zone Select 1, N '黑龙江省 ', 0
Union All Select 2, N '辽宁省 ', 0
Union All Select 4, N '哈尔滨 ', 1
Union All Select 5, N '北京 ', 0
Union All Select 6, N '沈阳 ', 2
Union All Select 7, N '长沙 ', 8
Union All Select 8, N '湖南 ', 0
select * into Test from zone
declare @cityNum int
declare @cityName varchar (20)
declare @cName varchar(20)
declare @pNum int
declare @cNum int
select @cityNum=count(pid) from test where pid=0
print @cityNum
while @cityNum> 0
begin
select @cityName=name from test where pid=0
print @cityName
select @pNum=
case
when @cityName= '湖南 ' then 8
when @cityName= '黑龙江省 ' then 1
when @cityName= '辽宁省 ' then 2
else 100
end
select @cNum=count(pid) from test where pid=@pNum
while @cNum> 0
begin
select @cName=name from test where pid=@pNum
print @cName
delete from test where name=@cName
select @cNum=@cNum-1
end
delete from test where name=@cityName
select @cityNum=@cityNum-1
end
[解决办法]
一天到晚游泳的鱼,SQL果然强噢。。
呵呵。顶了```
[解决办法]
select * from (select
ind = case pid
when 0 then id
else select top 1 b.id from zone a join zone b on a.pid = b.id where a.pid = c.pid
*
from zone c) d
order by d.ind