I’m learning how to program by creating a blog, and one of the requirements that I have is to increment the “count” column of a post category whenever a new blog post is created.
As for now, I have to use the following statements to accomplish this task:
INSERT INTO posts (..., ..., category_id) VALUES (..., ..., 5);
UPDATE categories SET count = count + 1 WHERE id = 5
Is there any way for me to combine these two into a single SQL statement? If not, is there a way to “automate” the increment of the count field whenever I created a new post with that category?
You can automate this by using a trigger.
Then, when you insert a row into posts (
INSERT INTO posts (..., ..., category_id) VALUES (..., ..., 5);), it will automatically increment your count.