N
N
Nube2018-06-11 18:14:54
PostgreSQL
Nube, 2018-06-11 18:14:54

How to get a list of parent IDs?

There is a comments table

comment (
  id_comment          integer PRIMARY KEY ,
  path                integer[] not null,
  content              text,
  rating              integer
)

Need to get high rated comment first works fine, but if a child comment has a higher rank than the parent or other comment it will output it first. And I would like to sort by rating only the first parent and those who do not have "children" in short, we have:
SELECT * FROM comment ORDER BY rating DESC LIMIT
id |  path   |    content                     | rating
----+---------+--------------------------------+---------
  1 | {1}     | я комментарий 1                | 1
  2 | {1,2}   | я дочь        комментария 1    | 5
  3 | {3}     | я комментарий 3                | 3
  4 | {4}     | я  комментарий 4               | 2
  
результат сортировки  должен быть :
 id |  path   |    content                     | rating
----+---------+--------------------------------+---------
  3 | {3}     | я комментарий 3                | 3
  4 | {4}     | я комментарий 4                | 2
  1 | {1}     | я комментарий 1                | 1
  2 | {1,2}   | я дочь комментария 1           | 5

I'm using the Materialized Path pattern.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Burov, 2018-06-11
@Nube

https://www.postgresql.org/docs/current/static/fun...
array_length

SELECT * FROM comment ORDER BY array_length(path, 1) ASC, rating DESC

D
d-stream, 2018-06-11
@d-stream

Isn't it better to recursively take the whole chain, and collect the rating of children like avg for example?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question