SQL - 如何使用另一个表中的计数进行排序

时间:2011-01-24 16:43:17

标签: sql mysql sql-order-by

1。博客

blogger_id
1 
2
3

2。帖子

post_from_blogger_id
1 
1
1
2
2
3

正如你可以看到博客№1发布的比其他人更多,博主№3少。问题是 如何构建一个选择所有博主的查询,并根据帖子的数量对它们进行排序?

6 个答案:

答案 0 :(得分:45)

 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

(注意:MySQL有一些特殊的语法,可以让你在不聚合所有值的情况下进行GROUP BY,它就是针对这种情况的。)

答案 1 :(得分:4)

使用子查询。

select * from (
    select post_from_blogger_id, count(1) N from Posts
    group by post_from_blogger_id) t
order by N desc

答案 2 :(得分:2)

试试这个:

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

这将连接2个表,并计算Posts表中的条目数。如果没有,则计数为0(IFNULL)。

答案 3 :(得分:2)

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

答案 4 :(得分:1)

尝试LEFT JOIN来解决这个问题

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

答案 5 :(得分:0)

我有同样的问题。这些答案对我没有帮助。我使用了这样的查询:

SELECT *
FROM company c
ORDER BY (select count(a.company_id) from asset a where a.company_id = c.id) DESC

这个问题:

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