简体   繁体   中英

Increment the number of "commentsNumber" in the post table for all comments in comments table that has a specific postId

This is the post table And this is the comments table

There is a way to encrease the value " commentsNumber " for each comments that has " postId " = post to increase the value?

I hope I made myself understood in some way

The idea was to increase the value of " commentsNumber " and then fetch the data so as to show the number of comments on the post. Of course, if there's a better way to handle this, suggestions are welcome.

I specify that initially the " commentsNumber " column was not present, if someone knows how to do it through a query and you think it's better, tell me

When including sample data in your question, do not insert images! Instead you should include a markdown table of data ( tableconvert.com makes this very easy) and/or the CREATE TABLE statements and INSERTS so we can quickly and easily reproduce your example/problem.


In the vast majority of cases, storing the redundant count of child records is considered premature optimisation (at best). RDBMSes can perform these simple tasks incredibly quickly and efficiently, as long as the data is indexed appropriately.

It should be calculated on the fly -

SELECT p.*, COUNT(c.id) AS commentsNumber
FROM posts p
LEFT JOIN comments c
    ON p.id = c.postId
GROUP BY p.id

It is important that there is an index on comments.postId but it should already be there as it is a foreign key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM