开发者

SQL - How To Order Using Count From Another Table

开发者 https://www.devze.com 2023-02-06 16:56 出处:网络
1. Bloggers blogger_id 1 2 3 2. Posts post_from_blogger_id 1 1 1 2 2 3 As you can see blogger №1 posted more than the others and blogger №3 less. The question is

1. Bloggers

blogger_id
1 
2
3

2. Posts

post_from_blogger_id
1 
1
1
2
2
3

As you can see blogger №1 posted more than the others and blogger №3 less. The question is how to build a query that selects all bloggers and so开发者_运维知识库rts them by the number of their posts?


 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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号