--列名:id,名称,所属id
create table t1(id int,mc varchar(20),ssid int)
go
insert into t1
select 1,'名称1',0
union all
select 2,'名称2',0
union all
select 3,'名称3',1
union all
select 4,'名称4',2
union all
select 5,'名称5',4
union all
select 6,'名称6',4
union all
select 7,'名称7',6
union all
select 8,'名称8',3
--delete from t1
select * from t1
/*
id mc ssid
1 名称1 0
2 名称2 0
3 名称3 1
4 名称4 2
5 名称5 4
6 名称6 4
7 名称7 6
8 名称8 3
*/
--传入的id=4时,将id=4及4以下的其他从属项排除掉,得到结果:
/*
id mc ssid
1 名称1 0
2 名称2 0
3 名称3 1
8 名称8 3
*/
请问这个查询怎么写?
------解决思路----------------------
with cte1 as (
select t1.* from t1 where id = 4
union all
select t1.* from t1 , cte1 where t1.ssid = cte1.id
)
select * from t1
except
select * from cte1
id mc ssid
----------- -------------------- -----------
1 名称1 0
2 名称2 0
3 名称3 1
8 名称8 3
(4 行受影响)
------解决思路----------------------
with cte1 as ... 这个,先查出 id =4 的这行,union all 后面的,是递归查出上级是 4 的这些行,注意是递归。
最后
select * from t1
except
select * from cte1
except 是一个减操作,刚才查出了 id = 4 的所有数据, 减掉他们,就是你的结果。