Postgres的无限自我加盟(Postgres infinite self join)

2019-11-05 05:23发布

所以,我有一篇文章,并在文章“意见” ..

评论让人们回复..,你可以回复回复..等等等等,这意味着最深的树根将是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有空PARENT_ID表是“主”的评论(又名不是回复)..我很想如果可能的话,如果children领域内得到填充本身(即回复的回复)

这甚至可能在Postgres? 还是我应该是获取所有Replies与加入他们Comments ,然后通过每一个试图找到它正确的输出地址迭代?

顺便说一句,我使用GoLang对我的后端和Gorm包访问我的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;

其结果:

这是近了一步。但是我需要的是有一个JSON对象返回看起来像

comments: [
  {
    comment_id: ...,
    username: ...,
    comment_body: ....,
    comment_likes: ....,
    children: [...]
  },
  {
    .....
  }
]

当里面的第一个项目comments的对象将是不答复的意见,并在children领域应与答复意见..和内部的意见填入children也应该有自己的children填充到答复该回复

Answer 1:

希望这是你的预期结果。 (我没有类似的东西在这里: https://stackoverflow.com/a/52076212/3984221 )

演示:分贝<>小提琴

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 )构建用于与空的儿童阵列,其中的儿童以后可以插入每个评论JSON对象。

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对象到全局对象的路径。



文章来源: Postgres infinite self join