Home  >  Q&A  >  body text

Main query and subquery - subquery not returning desired results

<p>我有以下用于评论系统的SQL查询。</p> <pre class="brush:php;toolbar:false;">SELECT `main`.`comment_id`, `main`.`comment`, `main`.`timestamp`, `main`.`replay_comment_id`, COUNT(`replay`.`comment_id`) AS replays FROM `posts_comments` AS `main` LEFT JOIN `posts_comments` AS `replay` ON `replay`.`replay_comment_id` = `main`.`comment_id` WHERE `main`.`post` = "107" AND (`main`.`replay_comment_id` IS NULL OR `main`.`comment_id` in ( SELECT `posts_comments`.`comment_id` FROM `posts_comments` WHERE `posts_comments`.`replay_comment_id` = `main`.`comment_id` ) ) GROUP BY `main`.`comment_id` ORDER BY `main`.`comment_id` ASC;</pre> <p>使用以下数据库结构和内部值:</p> <pre class="brush:php;toolbar:false;">|------ |Column|Type|Null|Default |------ |//**comment_id**//|int(10)|No| |post|int(10)|No| |author|int(10)|No| |replay_comment_id|int(10)|Yes|NULL |timestamp|int(10)|No| |comment|varchar(200)|No| == Dumping data for table posts_comments |19|107|12|NULL|1688801931|comment 1 |20|107|12|NULL|1688801995|comment 2 |21|107|13|20|1688801995|test 1 comment for comment 2 |22|107|12|20|1688801995|test 2 comment for comment 2 |23|107|12|222|1688801995|test 1 comment for other comment</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 days ago350

reply all(1)I'll reply

  • P粉521013123

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

    This method does not work. 19 and 20 satisfy main.replay_comment_id IS NULL, but in the subquery for 21, posts_comments.replay_comment_id = 19, this does not provide any results. Therefore, sub-comments 21 and 22 were not selected.

    Please check the following query to see if it gives you results.


    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 ;

    reply
    0
  • Cancelreply