Itâ€™s hard to describe this scenario precisely with limited title length. Basically, this is when you want to dedicate a field in â€˜categoryâ€™ table to store the number of articles or posts in â€˜postâ€™ table that fall into this category.
Previously, you had both â€˜categoryâ€™ table to store post categories and â€˜postâ€™ table to store posts. Each post must fall under a category for the sake of categorization referenced by a field named â€˜categoryâ€™ in table â€˜postâ€™ that bears the ID of the category in table â€˜categoryâ€™ that this post belongs to.
I hope I have made myself clear on this.
Now the problem is that you want to display the count of posts under each category and there are apparently a large number of them so preferably you donâ€™t want to count through them all each time a web page is loaded so as to reduce mysql server load.
The solution is obvious. Youâ€™d make an additional column for table â€˜categoryâ€™ arbitrarily named â€˜countâ€™ for example. And update it once thereâ€™s an addition to the posts or a deletion from the existing. Now how do we do that.
Assume that there are only 2 columns in the current â€˜categoryâ€™ table, one is ID and the other is TITLE. To create another category table from the existing one with an additional â€˜countâ€™ field:
CREATE TABLE category2 SELECT category.id AS id, category.title AS title, COUNT( post.category ) AS count FROM category, post WHERE post.category = category.id GROUP BY post.category
This would create a new table called â€˜category2â€™ thatâ€™s no different from the original â€˜categoryâ€™ table except for the additional column we just added: â€˜countâ€™.
Executing this single SQL query, not only is the new column created but they are also filled with the count of the posts that are assigned to each of the category.
The last task of this job will be to drop the original â€˜categoryâ€™ table and rename â€˜category2â€™ to â€˜categoryâ€™.
By the help of an extra temporary table, you can also add a number / count column by combining the following 2 tips:
- Create a temporary table of rows with id and count: counting records number.
- Transfer the statistics from the temporary table to the newly created column of the original table: update more than one rows with a single update query.