Best practize for count(*)

Robert9

Well-known member
With the both addons credits and shops from TH i have a wonderful time to learn working with addons. In both scripts are many things that could be done better from my pov. For example there is no pagination for purchased products and also none for the products itself. To make such a pagination i need

page
perPage
cnt_of_items

one way done here is to make a query for the rows of items (here done in transactions); every time someone watches a page, we have to count again and again and again.
Instead of this i could save the number of items in a category, like i could save the number of puchased items from a user.
I am not shure if i want to add another field to xf_user, because i may have some hundreds of people using the shop, but tenthousands and more users in the forum. This means a lot of nit used fields.

But for the categories we have less numbers, so this makes sense for me.
To make it perfect we can count the products while we save a product?

This is solved from different addons in different ways. Some people just count plus and minus one, when they move something from a category to another.
Some have function to recount also, some not.

Posts is something we can add, because we have many posts. And with a manual count or with a cron we can check the right numbers from time to time.
But with something small like products a recount on every save makes sense for me.

Are there any rules how to care for such things? The problem is always the same.
Count when needed or fetched from a field, save after a recount, just plus/minus one (and recount manually or by cron)

I would like to know what makes sense in which situation.
 
Normally adding and subtracting one should be plenty sufficient, as long as you can ensure that it doesn't get out of sync. However, a single count query on post operations is a pretty neglectible cost and offers an additional layer of protection against getting out of sync. It's really up to your preference.

You wouldn't want a recount on Cron however, if you opted for the first version. Only on explicit demand. Bulking that for all items will be a huge cost if you have many items, so you'd want to run that as rarely as possible. If it'd be needed regularly, opt for count on post ops.
 
Top Bottom