Hauptabfrage und Unterabfrage – Unterabfrage liefert nicht die gewünschten Ergebnisse
P粉505917590
P粉505917590 2023-07-24 15:42:03
0
1
349
<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 wird wiederholt FROM „posts_comments“ AS „main“. LEFT JOIN `posts_comments` AS `replay` ON `replay`.`replay_comment_id` = `main`.`comment_id` WO `main`.`post` = "107" AND (`main`.`replay_comment_id` IS NULL OR `main`.`comment_id` in ( SELECT `posts_comments`.`comment_id` AUS `posts_comments` WO `posts_comments`.`replay_comment_id` = `main`.`comment_id` ) ) GRUPPIERE NACH `main`.`comment_id` SORTIEREN NACH `main`.`comment_id` ASC;</pre> <p>使用以下数据库结构和内部值:</p> <pre class="brush:php;toolbar:false;">|------ |Spalte|Typ|Null|Standard |------ |//**comment_id**//|int(10)|Nein| |post|int(10)|Nein| |author|int(10)|No| |replay_comment_id|int(10)|Ja|NULL |timestamp|int(10)|Nein| |comment|varchar(200)|Nein| == Dumping von Daten für die Tabelle posts_comments |19|107|12|NULL|1688801931|Kommentar 1 |20|107|12|NULL|1688801995|Kommentar 2 |21|107|13|20|1688801995|test 1 Kommentar für Kommentar 2 |22|107|12|20|1688801995|Test 2 Kommentar für Kommentar 2 |23|107|12|222|1688801995|1 Kommentar für anderen Kommentar testen</pre> <p>是ID为20的评论的子评论.不应返回ID为23的评论.现在的查询只返回主要评论.</p><p>到我我想要的结果, 但是如果使用main.comment_id ,则无法得到结果,我无法理解为什么。对于任何评论和想法,将不胜感激。</p>
P粉505917590
P粉505917590

Antworte allen(1)
P粉521013123

这个方法行不通。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 ;
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!