1. Bloggers
blogger_id
1
2
3
2. Posts
post_from_blogger_id
1
1
1
2
2
3
As
Use subqueries.
select * from (
select post_from_blogger_id, count(1) N from Posts
group by post_from_blogger_id) t
order by N desc
SELECT b.*
FROM Bloggers AS b
LEFT JOIN (
SELECT post_from_blogger_id, COUNT(*) AS post_count
FROM Posts
GROUP BY post_from_blogger_id
) AS p ON b.blogger_id = p.post_from_blogger_id
ORDER BY p.post_count DESC
SELECT bloggers.*, COUNT(post_id) AS post_count
FROM bloggers LEFT JOIN blogger_posts
ON bloggers.blogger_id = blogger_posts.blogger_id
GROUP BY bloggers.blogger_id
ORDER BY post_count
(Note: MySQL has special syntax that lets you GROUP BY without aggregating all values, it's intended for exactly this situation).
try LEFT JOIN for this question
SELECT DISTINCT(Bloggers.blogger_id),
(select count(post_from_blogger_id) from Posts
where Posts.post_from_blogger_id=Bloggers.blogger_id) post_from_blogger_id FROM Bloggers
LEFT OUTER JOIN Posts ON Bloggers.blogger_id=Posts.post_from_blogger_id
ORDER BY post_from_blogger_id DESC
Try this:
SELECT B.blogger_id,
B.blogger_name,
IFNULL(COUNT(P.post_from_blogger_id ),0) AS NumPosts
From Blogger AS B
LEFT JOIN Posts AS P ON P.post_from_blogger_id = B.blogger_id
GROUP BY B.blogger_id, B.blogger_name
ORDER BY COUNT(P.post_from_blogger_id ) DESC
This joins the 2 tables, and counts the number of entries in the Posts
table. If there are none, then the count is 0 (IFNULL).
I had the same problem. These answers didn't help me. I used such a query:
SELECT *
FROM company c
ORDER BY (select count(a.company_id) from asset a where a.company_id = c.id) DESC
To this question:
SELECT *
FROM bloggers b
ORDER BY (select count(p.post_from_blogger_id) from posts p where p.post_from_blogger_id = b.blogger_id) DESC