SQL - How To Order Using Count From Another Table

空扰寡人 提交于 2019-12-02 17:12:51
 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).

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

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).

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
Sidharth Gusain

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!