首页  >  问答  >  正文

主查询和子查询 - 子查询未返回所需结果

<p>我有以下用于评论系统的SQL查询。</p>
SELECT
    `main`.`comment_id`,
    `主要`.`评论`,
    `主要`.`时间戳`,
    `main`.`replay_comment_id`,
    COUNT(`重播`.`comment_id`) AS 重播
FROM `posts_comments` AS `main`
左连接 `posts_comments` AS `replay` ON `replay`.`replay_comment_id` = `main`.`comment_id`
在哪里
    `main`.`post` = "107" AND (`main`.`replay_comment_id` 为 NULL 或 `main`.`comment_id` in ( SELECT
            `posts_comments`.`comment_id`
        从
            `帖子评论`
        在哪里
            `posts_comments`.`replay_comment_id` = `main`.`comment_id` ) )
通过...分组
    `main`.`comment_id`
订购依据
    `main`.`comment_id` ASC;</pre>
<p>使用以下数据库结构和内部值:</p>
|--------
|列|类型|空|默认
|------
|//**评论 ID**//|int(10)|否|
|帖子|int(10)|否|
|作者|int(10)|否|
|replay_comment_id|int(10)|是|NULL
|时间戳|int(10)|否|
|评论|varchar(200)|否|

== 转储表 posts_comments 的数据
|19|107|12|NULL|1688801931|评论 1
|20|107|12|NULL|1688801995|评论 2
|21|107|13|20|1688801995|测试评论2的1条评论
|22|107|12|20|1688801995|测试评论2的评论2
|23|107|12|222|1688801995|测试 1 条评论是否有其他评论</pre>
<p>期望的结果将返回ID为19和20的评论,因为它们是主要评论,以及ID为21和22的评论因为,它们是ID为20的评论的子评论。不宜返回ID为23的评论。现在的查询只返回主要评论。</p><p>在子查询中,如果我将main.comment_id替换为20,我可以获得我想要的结果,但是如果使用main.comment_id ,则无法得到结果,我无法理解为什么。对于任何评论和想法,都不会胜感激。</p>
P粉505917590P粉505917590428 天前356

全部回复(1)我来回复

  • P粉521013123

    P粉5210131232023-07-25 13:32:08

    这个方法行不通。19和20满足main.replay_comment_id IS NULL,但在21的子查询中,posts_comments.replay_comment_id = 19,这并没有提供任何结果。因此,子评论21和22没有被选中。

    请检查以下查询,看看是否能给您提供结果。


    SELECT 
                  p1.`comment_id`,
                  p1.`comment`,
                  p1.`timestamp`,
                  p1.`replay_comment_id`,
                  (
                    CASE
                      WHEN p1.`replay_comment_id` IS NULL THEN 1 
                      WHEN p1.`replay_comment_id` IN (SELECT DISTINCT comment_id FROM posts_comments) THEN 1 
                      ELSE 0 
                    END
                  ) relationFlg,
                  SUM(1- ISNULL(p2.`comment_id`)) hasChild 
                FROM
                  `posts_comments` p1 
                  LEFT JOIN `posts_comments` p2 
                    ON p1.`comment_id` = p2.`replay_comment_id` 
                GROUP BY 1 
                HAVING relationFlg = 1 
                ORDER BY 1 ;

    回复
    0
  • 取消回复