I’m trying to create views that would accumulate all the needed data from joined sources:
CREATE OR REPLACE VIEW dir AS
SELECT
dir_data.id,
dir_data.parent_id,
dir_data.name,
(owner.*)::owner, -- owner_id
FROM
dir_data
LEFT JOIN owner ON owner.id = dir_data.owner_id
For example, this allows to select owner’s data in easy way:
SELECT
id,
name,
(owner).id AS owner_id,
(owner).name AS owner_name,
((owner).company).name AS owner_company
FROM
dir
WHERE
id = 7
The problem is that I need to do a self-join with view dir (which is the vew being created) to convert parent_id field in similar way. PostgreSQL does not seem to like it, it says that relation "dir" does not exist.
Any hints?
Answer to Marcelo Cantos comment:
CREATE OR REPLACE VIEW dir AS
SELECT
...
FROM
dir_data
LEFT JOIN owner ON owner.id = dir_data.owner_id -- "standard" join
LEFT JOIN dir AS parent_dir ON parent_dir.id = dir_data.parent_id -- self-join, does not work
You can’t create a recursive view, but in the latest postgres you can make recursive queries: http://www.postgresql.org/docs/8.4/static/queries-with.html