SQL - How To Order Using Count From Another Table

后端 未结 6 1587
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-31 04:39

1. Bloggers

blogger_id
1 
2
3

2. Posts

post_from_blogger_id
1 
1
1
2
2
3

As

相关标签:
6条回答
  • 2021-01-31 04:57

    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
    
    0 讨论(0)
  • 2021-01-31 05:03
    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
    
    0 讨论(0)
  • 2021-01-31 05:04
     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).

    0 讨论(0)
  • 2021-01-31 05:09

    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 讨论(0)
  • 2021-01-31 05:15

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

    0 讨论(0)
  • 2021-01-31 05:15

    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
    
    0 讨论(0)
提交回复
热议问题