【问题标题】:How to sort nested set elements by rating of root element?如何通过根元素的评级对嵌套的集合元素进行排序?
【发布时间】:2018-05-11 17:49:32
【问题描述】:

树评论系统实现为简单的嵌套集

+---------+-----------+---------+---------+------- +--------+ |编号 | parent_id |半边天 | rgt |深度 |评级 | +---------+-----------+---------+---------+------- +--------+ | 4073406 | | 1058655 | 1058656 | 0 | 0 | | 3721850 | | 1058651 | 1058654 | 0 | 2 | | 4279470 | 3721850 | 1058652 | 1058653 | 1 | 0 | | 3682985 | | 1058649 | 1058650 | 0 | 1 | | 3643602 | | 1058647 | 1058648 | 0 | 0 | | 3182010 | | 1058643 | 1058646 | 0 | 3 | +---------+-----------+---------+---------+------- +--------+

左右键排序

SELECT * FROM COMMENTS ORDER BY rgt DESC; # firstly new
SELECT * FROM COMMENTS ORDER BY lft ASC;  # firstly old

这既简单又有效。

Q:如何根据线程中第一个[root]评论的评分对cmets进行排序,对其他非root cmets按左右键排序?

您可以在 YouTube 和其他一些网站上看到类似的实现,您可以在其中显示 newpopular cmets

【问题讨论】:

  • 您使用的是 MySQL 还是 Postgresql?不要标记未涉及的产品。
  • 我正在使用 postgresql

标签: sql postgresql nested-sets


【解决方案1】:

如果您的 cmets 只有两层深,我认为这会起作用...但是它们有可能超过两层吗?

with recursive cte as (
  select
    id, parent_id, lft, rgt, depth, rating,
    rgt * 1.0 as sort_order
  from comments
  where depth = 0

  union all

  select
    c.id, c.parent_id, c.lft, c.rgt, c.depth, c.rating,
    cte.rgt + 0.001 * c.depth
  from
    comments c
    join cte on
      c.parent_id = cte.id
  where
    c.depth != 0
)
select * from cte
order by sort_order

-- 编辑 2017 年 11 月 28 日--

我认为这段代码将处理多个级别。试试看,让我知道。

with recursive cte as (
  select
    id, parent_id, lft, rgt, depth, rating,
    rgt as sort_order1, id::text as sort_order2
  from comments
  where depth = 0

  union all

  select
    c.id, c.parent_id, c.lft, c.rgt, c.depth, c.rating,
    cte.rgt, cte.sort_order2 || ':' || c.id
  from
    comments c
    join cte on
      c.parent_id = cte.id
  where
    c.depth != 0
)
select
  id, parent_id, lft, rgt, depth, rating
from cte
order by sort_order1, sort_order2

【讨论】:

  • 可以是2级以上;(
  • @DimaMelnik -- 我做了一个我认为(希望)可能有所帮助的改变
  • 谢谢!您使用递归的想法对我非常有用!从 2017 年 11 月 28 日起,我对您的 SQL 查询进行了少量更正,从而解决了我的问题。
  • 作为 sort_order 我使用的只是简单的rating
【解决方案2】:

正确的 SQL 查询是(非常接近 Hambones 的答案)

WITH RECURSIVE r AS (
            SELECT c1.*, rgt AS _rgt, cached_votes_score AS rating
                FROM comments AS c1
                WHERE 
                    depth = 0 AND
            UNION ALL 
            SELECT c2.*, c2.rgt, rating AS rating
                FROM comments c2
                JOIN r ON c2.parent_id = r.id
        )
        SELECT * FROM r ORDER BY rating desc, _rgt DESC

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    相关资源
    最近更新 更多