SQL - How To Order Using Count From Another Table

后端 未结 6 1598
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  猫巷女王i
    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).

提交回复
热议问题