Skip to content
Advertisement

Using global list in recursive SQL query to avoid visted nodes

I have a self-referential table User:

Note that there are circular references.

I want to get all the followers, and followers of the followers, and so on of a user such that all the followers are presented in a flattened list, with their respective depths

For Adam:

Problem

I want to avoid the rows 3 and 4, which represents two problems:

  1. adam -> bob -> adam because it’s circular.

  2. adam -> bob -> charlie because charlie has already appeared before.

I’m able to solve problem #1 by using the following query by keeping a path column of visited ids in a branch

But it doesn’t resolve problem #2.

It gives the following result:

It still has problem #2 (duplicate charlie entry) because path column only keeps a list of ids in a specific branch.

How do I fix problem #2?

Possible solution

I can solve it in my code (Node.JS) by keeping a global cache (path equivalent).

Whereas, as far as I can tell, the above SQL query is the equivalent of something like:

How to I replicate my solution in code using a global cache in SQL?

Or any other way I can achieve the desired result?

I’m using Node.JS and PostgreSQL

Advertisement

Answer

If I understand correctly, you want to select only one row per follower after the recursive search:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement