首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

表的自连接查询?解决方案

2012-08-13 
表的自连接查询?declare @table table(id int ,name nvarchar(10),a varchar(10),superior_id int)insert

表的自连接查询?
declare @table table
(
  id int ,
  name nvarchar(10),
  a varchar(10),
  superior_id int
)
insert @table
select 266, N'河北', 002, 1 union all
select 282, N'长沙', 001, 1 union all
select 503, N'石家庄', 345, 266

id name a superior_id
266 河北 002 1  
282 长沙 001 1  
503 石家庄 345 266  


输出
266 河北 002 1
503 石家庄 345 266
查询出河北及所属的机构,关联字段为266?



上个帖子没说明白

[解决办法]

SQL code
WITH CTE AS (SELECT * FROM @TABLE WHERE ID = 266UNION ALLSELECT A.* FROM @TABLE A,CTE AS TWHERE A.superior_id  = T.ID)SELECT * FROM CTE
[解决办法]
SQL code
declare @table table(  id int ,  name nvarchar(10),  a varchar(10),  superior_id int)insert @tableselect 266, N'河北', 002, 1 union allselect 282, N'长沙', 001, 1 union allselect 503, N'石家庄', 345, 266select * from @table where id = 266union select * from @table t where exists(select 1 from @table where id = t.superior_id and t.superior_id = 266) 

热点排行