朋友列表的难题,高手帮帮忙

ybiori 2005-11-18 06:54:46
象360.yahoo.com的朋友列表怎么做的,a和b互为朋友,要选出a的朋友的朋友的朋友的朋友.....
如果这样设计表:
两个互为朋友的人是一条记录,sql怎么写?好像不能用一句写出来
uid1 uid2
1 2
2 3
3 4
3 5
7 1
8 9
...........

1的朋友们就是2,3,4,5,7
请大家来讨论讨论
...全文
186 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
ybiori 2005-11-19
  • 打赏
  • 举报
回复
好了,谢楼上的热心朋友们
明天结帐
Andy__Huang 2005-11-18
  • 打赏
  • 举报
回复
這種就是交叉連接查詢的,也可以用這樣的語句

select *
from (select uid1 from #tb)a
cross join (select uid2 from #tb)b
Andy__Huang 2005-11-18
  • 打赏
  • 举报
回复

create table #tb(uid1 int,uid2 int)
Insert into #tb
select 1,2
union all select 2,3
union all select 3,4
union all select 3,5
union all select 7,1
union all select 8,9

select * from #tb

select *
from (select uid1 from #tb)a , (select uid2 from #tb)b

uid1 uid2
---------------
1 2
2 2
3 2
3 2
7 2
8 2
1 3
2 3
3 3
3 3
7 3
8 3
1 4
2 4
3 4
3 4
7 4
8 4
1 5
2 5
3 5
3 5
7 5
8 5
1 1
2 1
3 1
3 1
7 1
8 1
1 9
2 9
3 9
3 9
7 9
8 9
zlp321002 2005-11-18
  • 打赏
  • 举报
回复
--用函数解决吧!
--参考一下:
create table A
(
ID int,
[姓名] varchar(10),
[上级ID] int
)
insert A
select 1,'A',0 union
select 2,'B',1 union
select 3,'C',1 union
select 4,'D',2 union
select 5,'E',3 union
select 6,'F',4 union
select 7,'G',5
go

--创建函数
create function f_nodes(@ID int)
returns varchar(8000)
as
begin
declare @tb table(ID int,[上级ID] int)
insert @tb
select ID,[上级ID] from A where ID=@ID

while @@rowcount>0
begin
insert @tb
select A.ID
,A.[上级ID]
from A
join @tb B on A.[上级ID]=B.ID
where A.ID not in(select ID from @tb)
end

declare @str varchar(8000)
set @str=''
select @str=@str+','+convert(varchar,[ID]) from @tb
return stuff(@str,1,1,'')
end
go

-- 查询示例
select dbo.f_nodes(1) '1的下级'
select dbo.f_nodes(2) '2的下级'
select dbo.f_nodes(3) '3的下级'

--删除测试环境
drop function f_nodes
drop table A
ytx98 2005-11-18
  • 打赏
  • 举报
回复
朋友的朋友的朋友的朋友到底转了几个弯啊,看来用一条语句很困难吧
ybiori 2005-11-18
  • 打赏
  • 举报
回复
沙发自己坐了,是不是表结构不合理?有没有更便于写sql的表结构?

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧