日期:2014-05-17  浏览次数:20361 次

|ZYCIIS| 如何在一个嵌套表中查询出记录的循环上级中是否有指定值? 谢谢
如有表
地区
ID  名称 上级ID
1   中国  null
2   广东  1
3   广州  2
4   深圳  2
5   天河区 3
-----------------------------
在MSSQL中:如何最快判断“ID=5”上面是否有"上级ID=1"的记录
在MYSQL中:如何最快判断“ID=5”上面是否有"上级ID=1"的记录

谢谢
------最佳解决方案--------------------
--> 测试数据:[TB]
if object_id('[TB]') is not null drop table [TB]
GO
create table [TB]([ID] int,[name] varchar(6),[parentid] int)
insert [TB]
select 1,'中国',null union all
select 2,'广东',1 union all
select 3,'广州',2 union all
select 4,'深圳',2 union all
select 5,'天河区',3

DECLARE @i INT ,@j INT
select @i=5,@j=1

;with test
AS 
(
SELECT * FROM TB WHERE id=@i UNION ALL
SELECT a.* FROM TB a INNER JOIN test b ON a.id=b.parentid
)
SELECT * FROM test WHERE id=@j

/*
ID          name   parentid
----------- ------ -----------
1           中国     NULL

(1 行受影响)


*/

drop table [TB]

------其他解决方案--------------------

/*
标题:SQL SERVER 2000中查询指定节点及其所有父节点的函数(字符串形式显示)
作者:爱新觉罗·毓华(十八年风雨,守得冰山雪莲花开)  
时间:2010-02-02
地点:新疆乌鲁木齐
*/

create table tb(id varchar(3) , pid varchar(3) , name varchar(10))
insert into tb values('001' , null  , '广东省')
insert into tb values('002' , '001' , '广州市')
insert into tb values('003' , '001' , '深圳市')
insert into tb values('004' , '002' , '天河区')
insert into tb values('005' , '003' , '罗湖区')
insert into tb values('006' , '003' , '福田区')
insert into tb values('007' , '003' , '宝安区')
insert into tb values('008' , '007' , '西乡镇')
insert into tb values('009' , '007' , '龙华镇')
insert into tb values('010' , '007' , '松岗镇')
go

--查询各节点的父路径函数(从父到子)
create function f_pid1(@id varchar(3)) returns varchar(100)
as
begin
  declare @re_str as varchar(100)
  set @re_str = ''
  select @re_str = name from tb where id = @id
  while exists (select 1 from tb where id = @id and pid is not null)
    begin
      select @id = b.id , @re_str = b.name + ',' + @re_str from tb a , tb b where a.id = @id and a.pid = b.id
    end
  return @re_str
end
go
--查询各节点的父路径函数(从子到父)
create function f_pid2(@id varchar(3)) returns va