Let’s say I have a table thread and a table response, where I store threads and responses to threads that user submit in a forum.
I am currently counting the responses a given thread has like this:
SELECT COUNT(id)
FROM response
WHERE container_id = THREAD_ID
But, wouldn’t it be better to just have another field (number_of_responses or something like that) in the thread table, add 1 to it every time it’s responded? Then the query turn into something like this:
SELECT number_of_responses
FROM thread
WHERE id = THREAD_ID
LIMIT 1
Yes, I’d be repeating data, but isn’t this approach more efficient? Or is it not recommended for some reason?
I don’t think you should use number_of_responses because it is generated data. You should only save in the database what the database can’t calculate himself.
When you are experiencing slow tables you should add indexes or optimize the tables some other way.