Skip to content
Advertisement

Fetching all parents in simple way with PostgreSQL

I have a table with a hierarchical structure:

JavaScript

I want to list all parents of the plan name Paints, so I can build a breadcrumb to navigate back. Using id = 6 I like to get:

JavaScript

I’m using postgresql with PHP, and thinking of efficient way to fetch all the parents as simple as possible.

Advertisement

Answer

Use recursive with query:

JavaScript

SqlFiddle

Instead of integer array of parent ids you can use text column to aggregate plan names:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement