How to speed up “select count(*)” with “group by” and “where”?

后端 未结 9 555
北恋
北恋 2020-12-07 10:28

How to speed up select count(*) with group by?
It\'s too slow and is used very frequently.
I have a big trouble using select count(*)

9条回答
  •  忘掉有多难
    2020-12-07 10:49

    If you have InnoDB, count(*) and any other aggregate function will do a table scan. I see a few solutions here:

    1. Use triggers and store aggregates in a separate table. Pros: integrity. Cons: slow updates
    2. Use processing queues. Pros: fast updates. Cons: old state can persist until the queue is processed so the user may feel a lack of integrity.
    3. Fully separate the storage access layer and store aggregates in a separate table. The storage layer will be aware of the data structure and can apply deltas instead of doing full counts. For example if you provide an "addObject" functionality within that you will know when an object has been added and thus the aggregate would be affected. Then you do only an update table set count = count + 1. Pros: fast updates, integrity (you may want to use a lock though in case several clients can alter the same record). Cons: you couple a bit of business logic and storage.

提交回复
热议问题