- PostgreSQL Recursion
- 19.3.2009
Here is that example code I promised about SQL recursion. Basically, blog_comment's have a parent_comment_id field that refers to the id of its parent comment. You would call the function below with something like:
SELECT * FROM get_comments(1);
- which would return the children comments of the blog_comment with id 1. I know the code can probably be cleaned up quite a bit, so understand this was my first time writing SQL logic while you're reading it.
CREATE FUNCTION get_comments(integer) RETURNS SETOF blog_comment AS $_$DECLARE tmp blog_comment%ROWTYPE; tmp2 blog_comment%ROWTYPE; BEGIN FOR tmp IN SELECT * FROM blog_comment WHERE parent_comment_id =$1 ORDER BY id ASC LOOP RETURN NEXT tmp; FOR tmp2 IN SELECT * FROM get_comments(tmp.id) LOOP RETURN NEXT tmp2; END LOOP; END LOOP; RETURN; END; $_$ LANGUAGE plpgsql;
Edit: I am very new to SQL functions, so if you have a better solution, feel free to share.

So where is get_child_comments! Post it now!
Reply
typo - should have been get_comments(tmp.id). Fixing it now.
Reply
With PostgreSQL 8.4 you'll be able to do write recursive queries so you could do something like this:
WITH RECURSIVE sub_comments(parent_id, id, comment) AS (
SELECT parent_id, id, comment FROM blog_comment WHERE id = 1
UNION ALL
SELECT bc.parent_id, bc.id, bc.comment
FROM blog_comments
JOIN sub_comments sc ON bc.id = sc.parent_id
)
SELECT * FROM sub_comments;
Take a look at http://www.postgresql.org/docs/8.4/static/queries-with.html
Reply
Thanks for the heads up! I will definitely be using this when it becomes available.
Reply