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 ;