I have a table denoting parent-child relations. The relations can go n-level deep.
I have created a sample table using the following query:
CREATE SEQUENCE relations_rel_id_seq
INCREMENT BY 1
NO MAXVALUE
NO MINVALUE
CACHE 1;
CREATE TABLE relations(
rel_id bigint DEFAULT nextval('relations_rel_id_seq'::regclass) NOT NULL PRIMARY KEY,
rel_name text,
rel_display text,
rel_parent bigint
);
I need to query the table and display the parent-child relations hierarchically. I’m still not getting an idea regarding how to query n-level deep using sql query.
For the sqlfiddle eg, the expected hierarchy of output:
rel1
rel11
rel111
rel112
rel1121
rel2
rel21
rel211
rel212
N.B: The value n, in n-level is unknown.
DB Design:
Is there any better way such a relation can be expressed in the
database for easy querying.?
With Postgres you can use a recursive common table expression:
SQLFiddle based on your example: http://sqlfiddle.com/#!11/59319/19
(I replaced the spaces for indention with underscores as SQLFiddle doesn’t display the spaces correctly)