Postgres无限自我加入

时间:2018-10-04 01:55:22

标签: sql postgresql go go-gorm

所以我有一篇文章,并对文章进行“评论”。

评论允许人们回复..您可以回复回复..依此类推,以此类推,最深的树根是N

快速模拟表的外观

Comments(id, news_id, user_id, body, likes)

Replies(id, parent_id) --> id here is = Comments.id

User(id, username, password)

News(id, title, body, image)

有没有一种查询Postgres数据库的方法,使我得到类似

的结果

因此Replies表中任何具有null parent_id为空的内容都是“主要”注释(aka不是答复)。如果可能的话,如果children字段填充在其内部,我希望(即回复的回复)

使用Postgres甚至可能吗?还是我应该将所有RepliesComments一起加入它们,然后遍历每个对象以尝试找到合适的目的地?

顺便说一句,我在后端使用GoLangGorm包来访问我的postgres数据库

编辑: 我正在使用此查询

with recursive commentss as (
  select r.id, r.parent, array[r.id] as all_parents, 
         c.body, u.username 
    from replies r 
          inner join comments c 
                  on c.id = r.id 
                join users u 
                  on u.id = c.user_refer 
   where (parent <> '') IS NOT TRUE 
   union all 
  select r.id, r.parent, c.all_parents || r.id, 
         co.body, u.username 
    from replies r 
          join comments co 
            on co.id = r.id 
          join users u 
            on u.id = co.user_refer 
          join commentss c 
            on r.parent = c.id 
               and r.id <> ALL (c.all_parents)
  ) 
   select * from commentss order by all_parents;

结果为:

enter image description here

离这更近了..但是我需要的是返回一个看起来像

的JSON对象
comments: [
  {
    comment_id: ...,
    username: ...,
    comment_body: ....,
    comment_likes: ....,
    children: [...]
  },
  {
    .....
  }
]

comments对象中的第一项应该是不是答复的注释,children字段应填充有已回复的注释..以及{{1 }}还应填充其children以回复该回复

1 个答案:

答案 0 :(得分:1)

希望这是您的预期结果。 (我在这里做了类似的操作:https://stackoverflow.com/a/52076212/3984221

demo: db<>fiddle

comments

id  body          user_id  likes  
--  ------------  -------  -----  
a   foo           1        1      
b   foofoo        1        232    
c   foofoofoo     1        23232  
d   fooFOO        1        53     
e   cookies       1        864    
f   bar           1        44     
g   barbar        1        54     
h   barBAR        1        222    
i   more cookies  1        1      

replies

id  parent_id  
--  ---------  
a   (null)     
b   a          
c   b          
d   a          
e   (null)     
f   (null)     
g   f          
h   f          
i   (null)     

结果

{
    "comments": [{
        "children": [],
        "username": "Mike Tyson",
        "comment_id": "i",
        "comment_body": "more cookies",
        "comment_likes": 1
    },
    {
        "children": [{
            "children": [],
            "username": "Mike Tyson",
            "comment_id": "b",
            "comment_body": "foofoo",
            "comment_likes": 232
        },
        {
            "children": [{
                "children": [],
                "username": "Mike Tyson",
                "comment_id": "c",
                "comment_body": "foofoofoo",
                "comment_likes": 23232
            }],
            "username": "Mike Tyson",
            "comment_id": "d",
            "comment_body": "fooFOO",
            "comment_likes": 53
        }],
        "username": "Mike Tyson",
        "comment_id": "a",
        "comment_body": "foo",
        "comment_likes": 1
    },
    {
        "children": [],
        "username": "Mike Tyson",
        "comment_id": "e",
        "comment_body": "cookies",
        "comment_likes": 864
    },
    {
        "children": [{
            "children": [],
            "username": "Mike Tyson",
            "comment_id": "g",
            "comment_body": "barbar",
            "comment_likes": 54
        },
        {
            "children": [],
            "username": "Mike Tyson",
            "comment_id": "h",
            "comment_body": "barBAR",
            "comment_likes": 222
        }],
        "username": "Mike Tyson",
        "comment_id": "f",
        "comment_body": "bar",
        "comment_likes": 44
    }]
}

查询

递归

WITH RECURSIVE parent_tree AS (
    SELECT 
        id, 
        NULL::text[] as parent_id,
        array_append('{comments}'::text[], (row_number() OVER ())::text) as path, 
        rc.children  
    FROM replies r
    LEFT JOIN LATERAL (SELECT parent_id, ARRAY_AGG(id) as children FROM replies WHERE parent_id = r.id GROUP BY parent_id) rc ON rc.parent_id = r.id
    WHERE r.parent_id IS NULL 

    UNION

    SELECT 
        r.id, 
        array_append(pt.parent_id, r.parent_id), 
        array_append(array_append(pt.path, 'children'), (row_number() OVER (PARTITION BY pt.parent_id))::text),
        rc.children      
    FROM parent_tree pt
    JOIN replies r ON r.id = ANY(pt.children)
    LEFT JOIN LATERAL (SELECT parent_id, ARRAY_AGG(id) as children FROM replies WHERE parent_id = r.id GROUP BY parent_id) rc ON rc.parent_id = r.id
), json_objects AS (
   SELECT c.id, jsonb_build_object('children', '[]'::jsonb, 'comment_id', c.id, 'username', u.name, 'comment_body', c.body, 'comment_likes', c.likes) as jsondata
   FROM comments c
   LEFT JOIN users u ON u.id = c.user_id
)
SELECT 
    parent_id, 
    path,
    jsondata
FROM parent_tree pt 
LEFT JOIN json_objects jo ON pt.id = jo.id
ORDER BY parent_id NULLS FIRST

唯一的递归部分在CTE parent_tree中。在这里,我正在寻找父母并建立一条道路。此路径是以后在正确位置插入json数据所必需的。

第二个CTE(json_objects)使用空的child数组为每个注释构建一个json对象,以后可以插入child。

LATERAL联接在答复表中搜索当前ID的子代,并给出一个包含其ID的数组。

最后的ORDER BY子句很重要。这样可以确保所有较高的节点都位于较低的节点(它们的子节点)之前。否则,由于无法在适当的时候不存在必要的父对象,因此稍后可能无法输入全局json对象。

构建最终的JSON对象

CREATE OR REPLACE FUNCTION json_tree() RETURNS jsonb AS $$
DECLARE
    _json_output jsonb;
    _temprow record;
BEGIN

    SELECT 
        jsonb_build_object('comments', '[]'::jsonb) 
    INTO _json_output;

    FOR _temprow IN
        -- <query above>
    LOOP
        SELECT jsonb_insert(_json_output, _temprow.path, _temprow.jsondata) INTO _json_output;
    END LOOP;

    RETURN _json_output;
END;
$$ LANGUAGE plpgsql;

不可能在递归中构建json对象,因为在查询中jsondata对象不是全局变量。因此,如果我将b作为子项添加到一个递归分支中的a中,则它将不在另一个将c作为子项添加的分支中。

因此有必要生成一个全局变量。这可以在一个函数中完成。使用计算出的路径和子对象,将最终的json一起构建起来非常简单:遍历结果集并将json对象添加到全局对象的路径中。