Maison  >  Questions et réponses  >  le corps du texte

Requête principale et sous-requête - la sous-requête ne renvoie pas les résultats souhaités

<p>我有以下用于评论系统的SQL查询。</p> <pre class="brush:php;toolbar:false;">SELECT `main`.`comment_id`, `principal`.`commentaire`, `main`.`horodatage`, `main`.`replay_comment_id`, COUNT(`replay`.`comment_id`) AS rediffusions DE `posts_comments` COMME `main` REJOIGNEZ À GAUCHE `posts_comments` AS `replay` ON `replay`.`replay_comment_id` = `main`.`comment_id` OÙ `main`.`post` = "107" ET (`main`.`replay_comment_id` EST NULL OU `main`.`comment_id` dans ( SELECT `posts_comments`.`comment_id` DEPUIS `posts_comments` OÙ `posts_comments`.`replay_comment_id` = `main`.`comment_id` ) ) PAR GROUPE `main`.`comment_id` COMMANDÉ PAR `main`.`comment_id` ASC;</pre>

使用以下数据库结构和内部值:</p> <pre class="brush:php;toolbar:false;">|------ |Colonne|Type|Null|Par défaut |------ |//**comment_id**//|int(10)|Non| |post|int(10)|Non| |auteur|int(10)|Non| |replay_comment_id|int(10)|Oui|NULL |timestamp|int(10)|Non| |comment|varchar(200)|Non| == Vidage des données pour la table posts_comments |19|107|12|NULL|1688801931|commentaire 1 |20|107|12|NULL|1688801995|commentaire 2 |21|107|13|20|1688801995|test 1 commentaire pour commentaire 2 |22|107|12|20|1688801995|test 2 commentaire pour commentaire 2 |23|107|12|222|1688801995|test 1 commentaire pour un autre commentaire</pre> <p>是ID为20的评论的子评论。不应返回ID为23 </p><p>在子查询中,如果我将main.comment_id替换为20,我可以得到我想要的结果,但是如果使用main.comment_id ,则无法得到结果,我无法理解为什么。对于任何评论和想法,将不胜感激。</p>

P粉505917590P粉505917590428 Il y a quelques jours351

répondre à tous(1)je répondrai

  • P粉521013123

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

    Cette méthode ne fonctionnera pas. 19 et 20 satisfont main.replay_comment_id IS NULL, mais dans la sous-requête pour 21, posts_comments.replay_comment_id = 19, cela ne fournit aucun résultat. Par conséquent, les sous-commentaires 21 et 22 n’ont pas été sélectionnés.

    Veuillez vérifier la requête suivante pour voir si elle vous donne des résultats.


    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 ;

    répondre
    0
  • Annulerrépondre