PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Postgres raggruppa per query

Per la tua query ricorsiva, puoi creare un percorso gerarchico usando questo trucco con 0 stringhe:Violino SQL

with recursive comment_list(article_comment_id, parent_comment_id, comment, article_id, comment_depth, comment_path) AS (
    select c.article_comment_id, 
           c.parent_comment_id, 
           c.comment, 
           c.article_id, 
           c.comment_depth,
           substr(CAST(1000000000+c.article_comment_id as varchar(1000)),2)
    from test_comment c
    where article_id = 100
      and parent_comment_id = 0

  union all

    select c.article_comment_id, 
           c.parent_comment_id, 
           c.comment, 
           c.article_id, 
           c.comment_depth,
           cl.comment_path || substr(CAST(1000000000+c.article_comment_id as varchar(1000)),2)
    from test_comment c
       join comment_list cl on c.parent_comment_id = cl.article_comment_id
)
select cl.article_comment_id,
     cl.comment_path, 
     cl.parent_comment_id,
     cl.comment, 
     cl.article_id,
     cl.comment_depth
from comment_list cl
order by cl.comment_path, cl.article_comment_id, cl.comment_depth;

Rilascia il GRUPPO PER. Vuoi "raggrupparli" per la visualizzazione, che in realtà è "ORDINA PER"

select cl.parent_comment_id, 
     cl.article_comment_id,
     cl.comment, 
     cl.article_id,
     cl.comment_depth
from comment_list cl
order by cl.parent_comment_id, cl.article_comment_id, cl.comment_depth;

Potresti aver bisogno o meno di cl.root_id nell'ordine per, quindi potrebbe essere

order by cl.root_id, cl.parent_comment_id, cl.article_comment_id, cl.comment_depth;