sql >> Database >  >> RDS >> PostgreSQL

Sorteer opmerkingen op threadpad en op aantal totale stemmen

Verzamel gewoon een andere array naast het pad, deze bevat niet alleen de id van elke opmerking in zijn pad, maar de total_votes (als een negatief getal) voor elke id. Daarna kunt u op die kolom bestellen.

WITH RECURSIVE first_comments AS (
(
 (
   SELECT id, text, level, parent_id, array[id] AS path, total_votes,
          array[-total_votes, id] AS path_and_votes
   FROM comments
   WHERE comments."postId" = 1 AND comments."level" = 0 
 )
)
UNION
 (
  SELECT e.id, e.text, e.level, e.parent_id, (fle.path || e.id), e.total_votes,
         (fle.path_and_votes || -e.total_votes || e.id)
  FROM
  (
    SELECT id, text, level, parent_id, total_votes FROM comments
    WHERE comments."postId" = 1
  ) e, first_comments fle
  WHERE e.parent_id = fle.id
 )
)
SELECT id, text, level, total_votes, path from first_comments ORDER BY path_and_votes ASC

SQLFiddle (alleen gegevens -- zonder de recursieve CTE)



  1. Een overzicht van ProxySQL-clustering in ClusterControl

  2. Maak een kamerentiteit voor een tabel met een veld met het LONG-gegevenstype in Sqlite

  3. Verhuizen naar MariaDB-back-up

  4. MySQL-fout 1 (HY000) Probleem bij het maken van bestand Errcode 2