即使使用多个 SQL 语句,答案也比我想象的要困难得多。
您的问题的简单答案是:创建一个包含所有兄弟关系的表。然后你可以这样查询:
select siblingid
from @allsiblings sa
where sa.userid = 3
一个音符。我使用 SQL Server 的语法,只是因为它恰好是最方便的数据库。我只使用 MySQL 中的功能,所以应该很容易翻译。
如何创建表@AllSiblings?好吧,继续添加不存在的兄弟对,直到不再添加。我们通过自连接获得对。
这里是代码(以前面的警告为准):
declare @allsiblings table (userid integer, siblingid integer);
declare @siblings table (userId int, siblingID int);
-- Initialize the @siblings table
insert into @siblings(userId, siblingID)
select 1 as userID, 2 as siblingID union all
select 1 as userID, 3 as siblingID union all
select 6 as userID, 5 as siblingID union all
select 5 as userID, 3 as siblingID union all
select 3 as userID, 1 as siblingID union all
select 4 as userID, 6 as siblingID;
-- Initialize all siblings. Note that both pairs are going in here
insert into @allsiblings(userid, siblingid)
select userId, siblingid from @siblings union
select siblingID, userid from @siblings
-- select * from @allsiblings
while (1=1)
begin
-- Add in new siblings, that don't exist by doing a self-join to traverse the links
insert into @allsiblings
select distinct sa.userid, sa2.siblingid
from @allsiblings sa join
@allsiblings sa2
on sa.siblingid = sa2.userid
where not exists (select * from @allsiblings sa3 where sa3.userid = sa.userid and sa3.siblingid = sa2.siblingid)
-- If nothing was added, we are done
if (@@ROWCOUNT = 0) break;
select * from @allsiblings;
end;