R
R
Ruslan2017-12-21 20:52:46
PostgreSQL
Ruslan, 2017-12-21 20:52:46

How to do recursive query sorting in postgresql?

Hello, tell me how to do it right so that sorting works correctly:
there is a table
id, pid, sort, name where pid is a foreign key on id, you need to pull out the whole tree with one request and sort by nesting and by the sort field
I make a request:

WITH RECURSIVE rec_category AS (
    (SELECT 1 AS depth, ARRAY[id] AS path, * FROM taa_periodical_category WHERE  pid = 0)
        UNION ALL
            SELECT r.depth + 1, r.path, n.*
            FROM   rec_category r 
            JOIN   taa_periodical_category n ON n.pid = r.id
    )
SELECT id, pid, depth, path, sort, name FROM rec_category ORDER BY path, sort;

I get:
id | pid | depth |  path        | sort | name
11 |   0 |     1 |         {11} |    2 | 'Категория 1'
13 |  11 |     2 |     {11}{11} |    4 | 'Категория 1 - 1'
16 |  11 |     2 |     {11}{11} |    7 | 'Категория 1 - 2'
18 |  11 |     2 |     {11}{11} |    8 | 'Категория 1 - 3'
17 |  11 |     2 |     {11}{11} |    9 | 'Категория 1 - 4'
19 |  18 |     3 | {11}{11}{18} |   10 | 'Категория 1 - 3 - 2'
20 |  18 |     3 | {11}{11}{18} |   11 | 'Категория 1 - 3 - 1'
12 |   0 |     1 |         {12} |    3 | 'Категория 2'
14 |  12 |     2 |     {12}{12} |    5 | 'Категория 2 - 1'
15 |  12 |     2 |     {12}{12} |    6 | 'Категория 2 - 2'

as you can see Category 1 - 3 - 2 and Category 1 - 3 - 1 come after Category 1 - 4 and should come after Category 1 - 3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Melkij, 2017-12-21
@Tiasar

This is how arrays are compared - element by element by the number of elements in the smaller array.
If the elements are identical - compare the lengths of the arrays . Therefore, arrays in this form are not suitable for you.
Maybe it's better to replace your adjacency list with a regular ltree materialized representation ?
Well, or at least you can replace your arrays with it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question