Let's assume I have the following tables:
drop table if exists city;
drop table if exists country;
drop table if exists world;
create table world (
id integer PRIMARY KEY,
name text not null,
population bigint not null
)
;
create table country (
id integer PRIMARY KEY,
world_id integer REFERENCES world (id),
name text not null,
population bigint not null
);
create table city (
id integer PRIMARY KEY,
country_id integer REFERENCES country (id),
name text not null,
population bigint not null
);
insert into world (id, name, population) values (1, 'World', 7125000000);
insert into country (id, world_id, name, population) values (2, 1, 'Austria', 8000000);
insert into country (id, world_id, name, population) values (3, 1, 'Poland', 38530000);
insert into city (id, country_id, name, population) values (4, 2, 'Vienna', 1741000);
insert into city (id, country_id, name, population) values (5, 2, 'Salzburg', 145000);
insert into city (id, country_id, name, population) values (6, 3, 'Warsaw', 1710000);
insert into city (id, country_id, name, population) values (7, 3, 'Stetin', 409000);
So basically a very simplified view on the world using 3 tables that are joined with each other. Now in order to get all the information I need, I could simply execute a query like
select
w.name,
c.name,
ci.name
from
world w
left outer join country c on (w.id = c.world_id)
left outer join city ci on (c.id = ci.country_id)
which gives me back the necessary data:
name | name | name
-------+---------+----------
World | Austria | Vienna
World | Austria | Salzburg
World | Poland | Warsaw
World | Poland | Stetin
For an small example like this, the data duplication in the result set might be okay. In my real world sample though, the result set is much bigger (200k rows) and much more columns to be queried. As the whole structure reminds of a tree structure, I am wondering, if it is possible to build a result set that looks a bit more like this:
id | parent | name | population
-------+----------+----------+------------
1 | null | World | 7125000000
2 | 1 | Austria | 8000000
3 | 1 | Poland | 38530000
4 | 2 | Vienna | 1741000
5 | 2 | Salzburg | 145000
6 | 3 | Warsaw | 1710000
7 | 3 | Stetin | 409000
All ids are unique among the different tables. Having only one table to represent and build the tree result set, I read, one can use with-queries but so far I did not find anything on how to achieve this for multiple tables involved.