Return product category with hierarchical info

From: Richard Klingler <richard(at)klingler(dot)net>
To: pgsql-sql(at)lists(dot)postgresql(dot)org
Subject: Return product category with hierarchical info
Date: 2022-01-05 12:19:11
Message-ID: 24fd6621-db02-24a1-0808-fd11a17fe262@klingler.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Good afternoon (o;

First of all, am I am totally no expert in using PGSQL but use it mainly
for simple web applications...

Now I have a table which represents the categories for products in a
hierarchical manner:

    id | name | parent

So a top category is represented with parent being 0:

    1 | 'Living' | 0

The next level would look:

    2 | 'Decoration' | 1

And the last level (only 3 levels):

    3 | 'Table' | 2

So far I'm using this query to get all 3rd level categories as I use the
output for datatables editor as a product can only belong to the lowest
category:

select id, name from category
where parent in (select id from category where parent in (select id from
category where parent = 0))

But this has a problem as more than one 3rd level category can have the
same name, therefore difficult to distinguish in the datatables editor
which one is right.

So now my question (finally ;o):

Is there a simple query that would return all 3rd levels category ids
and names together with the concatenated names of the upper levels?
Something like:

    3 | 'Table' | 'Living - Decoration'

thanks in advance

richard

PS: If someone could recommend a good ebook or online resource for such
stupid questions, even better (o;

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Oliveiros Cristina 2022-01-05 12:28:23 Re: Return product category with hierarchical info
Previous Message Tom Lane 2021-12-30 15:58:28 Re: ALTERING COLLATION