I have two queries below. The first one has a nested select. The second one makes use of a group by clause.
select
posts.*,
(select count(*) from comments where comments.post_id = posts.id and comments.is_approved = 1) as comments_count
from
posts
select
posts.*,
count(comments.id) comments_count
from
posts
left join comments on
comments.post_id = posts.id
group by
posts.*
From my understanding the first query is worse because it has to do a select for each record in posts where as the second query does not.
Is this true or false?
commentstoposts. Also, I've never grouped that way so I can't be sure, but even if it is legal syntax, yourGROUP BYwould be just as effective, and possibly faster, if you just didGROUP BY posts.post_id. Also, once properly written, I would expect the latter to be faster.