Categories: Development

MySQL Inner join with a COUNT and GROUP BY

How to do a MySQL Inner join combined with a COUNT and GROUP BY.

Assuming there are two tables one has details about “posts” and the other “categories” each post has a category which is linked to the id in the category table.

Outputing all the category names and how many posts that have assigned that category is done with this query:

SELECT posts.category, COUNT(*) AS the_count, category.name
FROM posts
         INNER JOIN category
                    ON posts.category = category.id
GROUP BY category.name
ORDER BY the_count DESC

The most confusing aspect is that COUNT(*) isnt assigned to any table which is completely fine because it only counts rows that meet the requirements. These requirments are category that are the same (grouped).

Share
Tags: How toMYSQL

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago