2013-02-01 3 views
1

나는 계층 적 주석이 필요하며 최신 루트 주석으로 정렬해야합니다.PostgreSQL 재귀 및 ORDER BY 최신 루트

내가이 테이블

CREATE TABLE comment 
(
    id serial PRIMARY KEY, 
    text text NOT NULL, 
    parent_id integer REFERENCES comment(id), 
    date timestamp 
); 

INSERT INTO comment (id, text, parent_id, date) VALUES (1, 'First Root Comment', NULL, '2013-01-02 20:00:00'); 
INSERT INTO comment (id, text, parent_id, date) VALUES (2, 'Second Root Comment', NULL, '2013-01-02 20:20:00'); 
INSERT INTO comment (id, text, parent_id, date) VALUES (3, 'Reply 1 to Root Comment', 1, '2013-01-02 20:01:00'); 
INSERT INTO comment (id, text, parent_id, date) VALUES (4, 'Reply 2 to Reply 1', 1, '2013-01-02 20:02:00'); 
INSERT INTO comment (id, text, parent_id, date) VALUES (5, 'Reply 1 to Second Root Comment', 2, '2013-01-02 20:21:00'); 
INSERT INTO comment (id, text, parent_id, date) VALUES (6, 'Reply 3 to Reply 1', 1, '2013-01-02 20:03:00'); 
INSERT INTO comment (id, text, parent_id, date) VALUES (7, 'Reply 1 to Reply 2', 4, '2013-01-02 20:02:30'); 

이 코드는 계층 적 표시해야 - http://www.sqlfiddle.com/#!12/96b37/2

WITH RECURSIVE cte (id, text, date, path, parent_id, depth) AS (

    SELECT id, 
     text, 
     date, 
     array[id] AS path, 
     parent_id, 
     1 AS depth 
    FROM comment 
    WHERE parent_id IS NULL 


    UNION ALL 

    SELECT comment.id, 
     comment.text, 
     comment.date, 
     cte.path || comment.id, 
     comment.parent_id, 
     cte.depth + 1 AS depth 
    FROM comment 
    JOIN cte ON comment.parent_id = cte.id 
    ) 
    SELECT id, text, date, path, depth FROM cte 
    ORDER BY path; 

을 결과는

Firt root comment (older root comment) 
- Reply 1 to First Root Comment 
- Reply 2 to First Root Comment 
-- Reply 1 to Reply 2 
- Reply 3 to First Root Comment 
Second Root Comment (newest root comment) 
- Reply 1 to Second Root Comment 

는하지만 정렬 최신 (이 결과를 원하는 것입니다 루트 코멘트)

Second Root Comment (newest root comment) 
- Reply 1 to Second Root Comment 
Firt root comment (older root comment) 
- Reply 1 to First Root Comment 
- Reply 2 to First Root Comment 
-- Reply 1 to Reply 2 
- Reply 3 to First Root Comment 

아이디어가 있으십니까? 감사합니다

답변

2

당신이 그들을 정렬 할 수 있도록 루트 코멘트에 대한 식별자의 일종이 필요합니다. 방법 :

WITH RECURSIVE cte (id, text, date, path, parent_id, depth) AS (
SELECT id, 
    text, 
    date, 
    array[id] AS path, 
    parent_id, 
    1 AS depth, 
    id as root 
FROM comment 
WHERE parent_id IS NULL 
UNION ALL 
SELECT comment.id, 
    comment.text, 
    comment.date, 
    cte.path || comment.id, 
    comment.parent_id, 
    cte.depth + 1 AS depth, 
    root 
FROM comment 
JOIN cte ON comment.parent_id = cte.id 
) 
SELECT id, text, date, path, depth FROM cte 
ORDER BY root desc, path; 
+0

감사합니다. http://www.sqlfiddle.com/#!12/96b37/3 – user2032789