declare @f table(id1 int, id2 int, primary key (id1, id2));
insert into @f
values
(1, 2), (2, 1), (1, 3), (3, 1), (2, 3), (3, 2), (3, 4), (4, 3), (4, 5), (5, 4);
insert into @f
select distinct
a.id1, c.id1
from
@f a join
@f b on b.id1 = a.id2 join
@f c on c.id1 = b.id2
where
a.id1 <> c.id1 and
not exists(select 1 from @f where id1 = a.id1 and id2 = c.id1);
select * from @f;