I would like to list the Posts with the most Likes per Blog.
Assuming that the posts
table contains a blog_id
, I think this would satisfy your needs:
SELECT p.id AS post_id, p.blog_id, COUNT(1) AS like_count
FROM posts p
INNER JOIN likes l ON (p.id = l.post_id)
GROUP BY p.id, p.blog_id
ORDER BY COUNT(1) DESC
you didn't specify how many of the top posts per blog you needed, so this will return all of them, in order of the most likes, regardless of which blog the post comes from.
If you only want the top post per blog, then it's considerably more complicated in MySQL:
SELECT v.post_id, v.blog_id, v.like_count
FROM (
SELECT p.id AS post_id, p.blog_id, COUNT(1) AS like_count
FROM posts p
INNER JOIN likes l ON (p.id = l.post_id)
GROUP BY p.id, p.blog_id
) v
INNER JOIN (
SELECT MAX(t.like_count) AS like_count, t.blog_id
FROM (
SELECT p.id AS post_id, p.blog_id, COUNT(1) AS like_count
FROM posts p
INNER JOIN likes l ON (p.id = l.post_id)
GROUP BY p.id, p.blog_id
) t
GROUP BY t.blog_id
) max_post ON (max_post.like_count = v.like_count AND max_post.blog_id = v.blog_id);
You can see the fiddle for this, here.
Caveat - if two posts for the same blog share the maximum like count for that blog then they will both appear in the results.