So I have a table companyinfo that has data like so:
company | role | person
--------|--------------|------------
Google | dev | John
Google | tester | Bob
Facebook| manager | Alex
Facebook| blah | Bob
I want to find through how many "connections" does John know people. So that if John and Bob worked at Google John knows Bob through 1 connection, but if John knows Bob and Bob knows Alex than John also knows alex by extension, but through Bob meaning 2 connections
I understand this as quite simple graph problem to solve in code but I have been trying to figure out how to write recursive sql to do this for several hours and only came up with:
WITH RECURSIVE search_graph(person, company, n) AS (
SELECT s.person, s.company, 1
FROM companyinfo s
WHERE s.person = 'John'
UNION
SELECT s.person, s.company, n+1
FROM companyinfo s, search_graph sg
WHERE s.person = 'Alex'
)
SELECT * FROM search_graph limit 50;
But it obviously does not work, yes it does find Alex, but not because of following connection through bob and loops infidelity hence limit 50
Clarification: If two people worked at the same company we assume they know each other. So that graph would look something like this:
|John|--dev--|Google|--tester--|Bob|--blah--|Facebook|
Such that people and companies are nodes and roles are edges.
companyinfodoesn't have any information about connections between people.