1

I have a table that looks like this:

stuff
    id integer
    content text
    score double
    children[] (an array of id's from this same table)

I'd like to run a query that selects all the children for a given id, and then right away gets the full row for all these children, sorted by score.

Any suggestions on the best way to do this? I've looked into WITH RECURSIVE but I'm not sure that's workable. Tried posting at postgresql SE with no luck.

3 Answers 3

3

The following query will find all rows corresponding to the children of the object with id 14:

SELECT *
FROM unnest((SELECT children FROM stuff WHERE id=14)) t(id)
     JOIN stuff USING (id)
ORDER BY score;

This works by finding the children of 14 as array first, then we convert it into a table using the unnest function, and then we join with stuff to find all rows with the given ids.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thanks @redneb
1

The ANY construct in the join condition would be simplest:

SELECT c.*
FROM   stuff p
JOIN   stuff c ON id = ANY (p.children)
WHERE  p.id = 14
ORDER  BY c.score;

Doesn't matter for the query whether the array of children IDs is in the same table or different one. You just need table aliases here to be unambiguous.

Related:

Comments

0

Similar solution:

With Postgres you can use a recursive common table expression:

with recursive rel_tree as (
   select rel_id, rel_name, rel_parent, 1 as level, array[rel_id] as path_info
   from relations 
   where rel_parent is null
   union all
   select c.rel_id, rpad(' ', p.level * 2) || c.rel_name, c.rel_parent, p.level + 1, p.path_info||c.rel_id
   from relations c
     join rel_tree p on c.rel_parent = p.rel_id
)
select rel_id, rel_name
from rel_tree
order by path_info;

Ref: Postgresql query for getting n-level parent-child relation stored in a single table

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.