views:

171

answers:

2

Hello!

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
+3  A: 

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

Michael Krelin - hacker
I know about recursive queries, have used them, but that's not what I'm looking for.
binaryLV
Well, the answer is still there - "You can't create a recursive view".
Michael Krelin - hacker
A: 
WITH    RECURSIVE dir AS
        (
        SELECT  dir_data.id,
                dir_data.parent_id,
                dir_data.name,
                owner
        FROM    dir_data
        LEFT JOIN
                owner
        ON      owner.id = dir_data.owner_id
        WHERE   dir_data.id = 7
        UNION ALL
        SELECT  dir_data.id,
                dir_data.parent_id,
                dir_data.name,
                owner
        FROM    dir
        JOIN    dir_data
        ON      dir_data.id = dir.parent_id
        LEFT JOIN
                owner
        ON      owner.id = dir_data.owner_id
        )
SELECT  *
FROM    dir
Quassnoi