开发者

Handling lots of COUNT queries for a report

I am putting together a report that shows statistical information about products for a company that owns those products. This report, in the form I need, contains as many as 150 'counts', because we are filling the table with the counts for 12 product types against 15 different statistical categories.

Here's the set up of the models. I'm afraid it's a little complicated!

Company is the entity accessing the report.

Company has many Products through Matchings; and  
Product has many Companies through Matchings.

Matching belongs_to Order.

Example report:
___________|_Available/Active/Light   Available/Active/Heavy   (+12 columns)__
Perishable |
Intangible |
(+10 rows) |

The product types are in the Product table (they run down the left side of the report). The categori开发者_如何学Goes across the top of the report are combinations of three criteria: two from Product and one from Order.

Example - for one cell in the Perishable row, show me how many matchings exist for whom the order type is 'active', the product's weight is 'light' and the product status is 'available'.

On its own the above query is not too bad, but if I keep going like this I'm going to have ~170 queries for this report - both an inelegant and highly impractical solution. Is there a magic ActiveRecord way to deal with this scenario?


You could always create a background job to run regularly and pre-cache the results, or pre-generate the entire report. This would free your users from having to sit and wait for 170 queries to run, and I assume it would be acceptable to have slightly stale results.

As for the elegance and practicality of it, the only magic you could use is SQL. Your object model wasn't built for reporting, don't feel bad about using a tool that was.


There is a statistics gem that does this sort of thing. It does allow you to cache the statistics.

I've used it for lightweight statistics like counts and averages but have never taken benchmarks, which is definitely something you'll want to do if performance is a concern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜