【问题标题】:Selecting All Replies with parent comment using single SQL query使用单个 SQL 查询选择所有带有父评论的回复
【发布时间】:2014-12-12 06:17:03
【问题描述】:

我有一个用于存储 cmets 的表,其结构如下:

cmets

ID | post_id | comment        | parent    
1  |  1      | hello world    | null
2  |  1      | reply 1        | 1
3  |  1      | reply 2        | 1
4  |  1      | reply 3        | 1

我想使用单个 sql 查询获取父评论及其所有回复。 目前我正在使用嵌套查询来检索特定父评论的回复,我知道这不是最佳实践。 我需要使用单个查询来完成此操作。

我当前的sql查询sn-p是:

parent_id =("select id,comment from comments where post_id='1' and parent='null'")["id"]

loop{       
      "select comment from comments where post_id='1' and parent= parent_id"
    }

我正在使用这些嵌套查询来获取 cmets 及其回复,使用单个查询实现这一点的最佳做法是什么?

【问题讨论】:

  • 所有条目的 postID = 1 那么你为什么要检查 parent_ID 或 parent
  • postID = 1 表示所有父评论和子 cmets 都属于 postID 1。我需要使用单个查询检索父评论及其所有回复。在父 paret 评论下显示回复
  • 顺便说一句你是对的。我必须弄清楚!谢谢

标签: c# sql


【解决方案1】:

我认为这个查询足以获取命令的所有记录(父+子)。

select id,comment from comments where post_id='1'

另外,当您想分别识别父母和孩子时。在选择查询中也获取 parentID。

select id,comment, parent from comments where post_id='1'

在c#代码中可以找到parent(parent为null)和child(Has parent as 1)。

【讨论】:

  • 但这里有一个问题,我不想一次加载所有回复,我只需要显示 3 个依赖于特定父评论。现在呢?
  • 您打算如何一一获得回复([123]、[456]、[789])。你问我如何识别每个包(3 个回答)??
  • 在页面加载时,对于特定的父评论,只有 3 个回复[1,2,3]。之后会有一个 AJAX 调用来检索相同父评论的更多回复 [4,5,6...]
  • 在 PageLoad 上使用 select top 4 id,comment, parent from cmets where post_id='1' order by id asc 之类的查询。然后在 Ajax - 发送回复和查询的最后一个 ID:select top 3 id,comment, parent from cmets where post_id='1' and id > [LastID]
【解决方案2】:

这样试试

select t.id,t1.comment from table1 t inner join table t1 on t1.id=t.parentid
and t.parentid is not null and t1.parentid is null

【讨论】:

    【解决方案3】:

    这就是我所做的:

    1. 根据您的问题创建表格。
    2. 用您问题中的测试数据填充它。
    3. 创建一个 CTE 查询,返回您期望的结果。

    解决方案的关键是 WITH RECURSIVE 公用表表达式。

    create table post_comment(
        id serial not null primary key,
        post_id int not null,
        comment text,
        parent_id int
    );
    
    insert into post_comment(post_id, comment, parent_id) values(1, 'hello world', null);
    insert into post_comment(post_id, comment, parent_id) values(1, 'reply 1', 1);
    insert into post_comment(post_id, comment, parent_id) values(1, 'reply 1', 1);
    insert into post_comment(post_id, comment, parent_id) values(1, 'reply 1', 1);
    
    with recursive comments(c) as (
        select * from post_comment where id = 1
    union all
        select * from post_comment where parent_id = 1
    )
    select * from comments;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-03
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 2021-02-01
      相关资源
      最近更新 更多