我正在尝试创建可以累积所有联接来源所需数据的视图:
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
(正在创建的vew)进行自联接,以类似的方式转换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
答案 0 :(得分:3)
您无法创建递归视图,但在最新的postgres中,您可以进行递归查询:http://www.postgresql.org/docs/8.4/static/queries-with.html
答案 1 :(得分: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