I have a table Answer and Many to Many table Link (Answer n-n Answer)
Link have 2 column : from_id and to_id reference to answer_id. I want get all descendant of answer by answer_id ( from_id in Link ).
I have written function as below :
CREATE OR REPLACE FUNCTION getAllChild(_answer_id BIGINT)
RETURNS SETOF BIGINT AS $$
DECLARE r link;
BEGIN
FOR r IN
SELECT * FROM link
WHERE from_id = _answer_id
LOOP
RETURN NEXT r.to_id;
RETURN QUERY SELECT * FROM getAllChild(r.to_id);
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql STRICT;
SELECT * FROM getAllChild(1);
The result is fine if to_id not duplicate with from_id that already got otherwise I will get recursive infinity.
My question is how I can make loop skip the existed to_id to call getAllChild() in RETURN QUERY
IF r.to_id <> r.from_id THEN <recursive call> END? -- With recursive CTEs you could solve this without a function.