SET search_path='tmp';
DROP TABLE targets CASCADE;
CREATE TABLE targets
(id integer not null primary key
, parent_id integer references targets(id)
, expected_target integer
);
INSERT INTO targets(id,parent_id,expected_target) VALUES
(1,NULL, 1000), (2,1, 500), (3,2, 200);
WITH RECURSIVE zzz AS (
SELECT t0.id, t0.parent_id
, 0::integer AS level
, t0.expected_target
FROM targets t0
WHERE t0.parent_id IS NULL
UNION
SELECT t1.id, t1.parent_id
, 1+zzz.level AS level
, t1.expected_target
FROM targets t1
JOIN zzz ON zzz.id = t1.parent_id
)
SELECT * FROM zzz
;
OUTPUT:
SET
DROP TABLE
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index "targets_pkey" for table "targets"
CREATE TABLE
INSERT 0 3
id | parent_id | level | expected_target
----+-----------+-------+-----------------
1 | | 0 | 1000
2 | 1 | 1 | 500
3 | 2 | 2 | 200
(3 rows)
UPDATE:如果你不想整棵樹,真正的樹,不過是樹而只是它的一個子樹的一部分,當然你也可以改變條件位:
WITH RECURSIVE zzz AS (
SELECT t0.id, t0.parent_id
, 0::integer AS level
, t0.expected_target
FROM targets t0
-- WHERE t0.parent_id IS NULL
WHERE t0.id = 2
UNION
SELECT t1.id, t1.parent_id
, 1+zzz.level AS level
, t1.expected_target
FROM targets t1
JOIN zzz ON zzz.id = t1.parent_id
)
SELECT * FROM zzz
;
此數據庫結構是否「鎖定」?我想不出任何使用標準SQL進行這種操作的高性能方式(7級自連接並不是我建議的) – 2012-04-02 09:29:32
它看起來像[ltree](http://www.postgresql。 org/docs/current/static/ltree.html)模塊是爲了解決 – 2012-04-02 10:34:49
@JoachimIsaksson 7個自連接有什麼問題..它是完全合理的,如果層數保證;)但我不明白什麼是*預期目標* - 結果應該是行還是列? – Aprillion 2012-04-02 10:55:15