M
M
McMike2017-04-04 11:13:24
PostgreSQL
McMike, 2017-04-04 11:13:24

How to select all subcategories?

There is a catalog with categories, with unlimited nesting. Everything is stored in postgres, a regular table with id and parent_id fields from itself.
How to select all subcategories for the specified id?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Gornostaev, 2017-04-04
@McMike

Use a recursive CTE :

with recursive r as (
    select
      id, parent_id, name
    from catalog_category
    where id = 8
  union
    select
      cc.id, cc.parent_id, cc.name
    from catalog_category as cc
    join r
      on cc.parent_id = r.id
)
select id, name from r where id <> 8;

This query selects all child categories of the category with ID = 8.

L
lega, 2017-04-04
@lega

If you need to quickly and in one request, then each element should contain an array (+ index) of all its parents.

F
freeExec, 2017-04-04
@freeExec

How to display category tree from database (Java / jsp)?

M
McMike, 2017-04-20
@McMike

I also found an article)) https://habrahabr.ru/post/269497/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question