标题:玩玩SQL的递归
只看楼主
mywisdom88
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:190
帖 子:3125
专家分:8340
注 册:2015-3-25
结帖率:98.96%
 问题点数:0 回复次数:4 
玩玩SQL的递归
-- 用SQL的递归处理家族关系
create table family(fid int,Relation varchar(25),fname varchar(25),pid int)
insert into family values(1,'父亲','A0000001',0)
insert into family values(2,'配偶','B0000001',1)

insert into family values(3,'父子','A0001001',1)
insert into family values(4,'父女','A0001002',1)
insert into family values(5,'父子','A0001003',1)

insert into family values(6,'配偶','C0000001',3)
insert into family values(7,'父子','A0002001',3)
insert into family values(8,'父女','A0002002',3)

insert into family values(9,'配偶','D0000001',5)
insert into family values(10,'父女','A0003001',5)
insert into family values(11,'父子','A0003002',5)

insert into family values(12,'配偶','E0000001',4)

insert into family values(13,'配偶','F0000001',11)
insert into family values(14,'父子','A0004001',11)
insert into family values(15,'父女','A0004002',11)
insert into family values(16,'父女','A0004003',11)
select * from family
搜索更多相关主题的帖子: 递归 into values SQL insert 
2022-07-15 17:08
mywisdom88
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:190
帖 子:3125
专家分:8340
注 册:2015-3-25
得分:0 
-- 查 Fid=5的,祖先和子孙,
with fm1(fid,Relation,fname,pid) -- 查祖先递归
as
(select fid,Relation,fname,pid from family where fid=5
 union all
 select b1.* from family b1 inner join fm1 on fm1.pid = b1.fid) , -- 别忘记这个逗号,多个CTE,中间用逗号

fm2(fid,Relation,fname,pid) -- 查子孙递归
as
(select fid,Relation,fname,pid from family where fid=5
 union all
 select b2.* from family b2 inner join fm2 on b2.pid = fm2.fid and b2.Relation<>'配偶')

select * from fm1
union
select * from fm2
union
select fm.* from family fm inner join fm1 on fm.pid=fm1.fid and fm.Relation='配偶'
union
select fm.* from family fm inner join fm2 on fm.pid=fm2.fid and fm.Relation='配偶'
order by pid
2022-07-15 17:11
mywisdom88
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:190
帖 子:3125
专家分:8340
注 册:2015-3-25
得分:0 
-- 查 Fid=11,祖先和子孙,只改变2楼的 fid=11,此时,FID=10的没了,也就是FID=11的姑姑不显示了。因为姑姑不属于11的祖先

2022-07-15 17:17
mywisdom88
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:190
帖 子:3125
专家分:8340
注 册:2015-3-25
得分:0 
-- 查 Fid=3,祖先和子孙,只改变2楼的 fid=3,此时
2022-07-15 17:19
mywisdom88
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:190
帖 子:3125
专家分:8340
注 册:2015-3-25
得分:0 
原来,SQL的递归这么简单的,要SQL2005版本以上的才有这个功能,CTE公用表表达式
2022-07-15 17:25



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-509571-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.068525 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved