1

我正在尝试创建可以从连接源中累积所有所需数据的视图:

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

例如,这允许以简单的方式选择所有者的数据:

SELECT
    id,
    name,
    (owner).id AS owner_id,
    (owner).name AS owner_name,
    ((owner).company).name AS owner_company
FROM
    dir
WHERE
    id = 7

问题是我需要使用视图进行自连接dir(这是正在创建的视图)以parent_id类似的方式转换字段。PostgreSQL 似乎不喜欢它,它说relation "dir" does not exist.

有什么提示吗?


对 Marcelo Cantos 评论的回答:

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
4

2 回答 2

3

您无法创建递归视图,但在最新的 postgres 中,您可以进行递归查询:http ://www.postgresql.org/docs/8.4/static/queries-with.html

于 2010-05-20T10:03:03.040 回答
0
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
于 2010-05-20T10:06:53.520 回答