简体   繁体   中英

Mysql query to search posts and comments, return total comment count

Am trying to write a query that

  1. Searches tables Posts and Comments for a string
  2. Returns matching Posts along with their total comment count if there is a match on either table.

I have:

SELECT Posts.id, Comments.id, Count(DISTINCT Comments.id)
FROM Posts 
LEFT JOIN Comments ON Comments.postid = Posts.id 
WHERE ( Posts.text LIKE '%test%' 
          OR ( Comments.text LIKE '%test%'  
          AND Comments.deleted = false ) ) 
       AND Posts.approved = true 
       AND Posts.deleted = false 
GROUP BY Posts.id

The problem with this query is that the where is filtering my Comments.id count, so instead of returning the total number of comments in the post, it returns the number of comments matching 'test'. How can I achieve what I want in a single query?

Actually GROUP BY clause is not needed:

SELECT Posts.id, 
    ( SELECT COUNT(*) FROM Comments c 
      WHERE c.postid = Posts.id AND c.deleted = false
    ) AS total_post_comments
FROM Posts 
WHERE Posts.approved = true 
    AND Posts.deleted = false 
    AND (
        Posts.text LIKE '%test%'
        OR EXISTS(
            SELECT 1 FROM Comments
            WHERE Comments.text LIKE '%test%'
              AND Comments.deleted = false
              AND Comments.postid = Posts.id
        )
    )

If I understand correctly, you want all posts where the post or a comment contains the string of interest. For the ones that match, you want the total comment count.

For this, using having :

SELECT p.id, Count(c.id)
FROM Posts p JOIN
     Comments c
     ON c.postid = p.id 
GROUP BY p.id
WHERE p.approved = true AND
      p.deleted = false 
HAVING p.text LIKE '%test%' OR
       SUM( c.text LIKE '%test%' AND c.deleted = false ) > 0;
      

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM