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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago