I have a table of Likes (uid1 likes uid2) and given a specific userID (uid) I need to find all the people that like him, or anyone who likes him, and so on and so forth.
with recursive Hierarchy(uid, Level)
as
(
select
uid1 as uid, 1 as Level
from
Likes l
where
l.uid2 = 1 --parameter will go here
union all
select
l.uid1, lh.Level + 1
from
Likes l
inner join Hierarchy lh
on l.uid2 = lh.uid
where l.uid1 not in (select uid from Hierarchy) --this is wrong syntax in postgresql
)
select * from Hierarchy
the problem appears when for instance given the following values in table Likes
2,1 (2 likes 1)
3,1 (3 likes 1)
4,1 (4 likes 1, 1 is popular)
3,4 (3 likes 4)
4,3 (4 likes 3)
there is a circle in the likes hierarchy, and I wanted to add only items not the previous iteration (hence the NOT IN).
So is it possible to insert a limitation only to add new uids?
Based on this template:
(http://www.postgresql.org/docs/8.4/static/queries-with.html)
you get: