Reputation: 81
Am trying to write a query that
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?
Upvotes: 2
Views: 423
Reputation: 2593
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
)
)
Upvotes: 2
Reputation: 1269923
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;
Upvotes: 0