日期:2014-05-18  浏览次数:20381 次

表的自连接查询?
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 = 266
UNION ALL
SELECT A.* FROM @TABLE A,CTE AS T
WHERE 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 @table
select 266, N'河北', 002, 1 union all
select 282, N'长沙', 001, 1 union all
select 503, N'石家庄', 345, 266
select * from @table where id = 266
union 
select * from @table t where exists
(select 1 from @table where id = t.superior_id and t.superior_id = 266)