小编dvc*_*crn的帖子

加速数百万行的计数查询

假设一个充满产品的数据库。一个产品可以恰好属于 1 个集合并且由用户创建。数据库的粗略规模:

  • 产品:52.000.000
  • 收藏:9.000.000
  • 用户:大约 9.000.000

我正在尝试检索用户拥有的产品+集合的数量,以及每个集合中的产品数量(该信息应该在所有 x 天生成并在 ElasticSearch 中编入索引)。

对于用户查询,我目前正在做这样的事情:

      SELECT
        users.*,
        (SELECT
          count(*)
        FROM
          products product
        WHERE
          product.user_id = user.id
        ) AS product_count,
        (SELECT
          count(*)
        FROM
          collections collection
        WHERE
          collection.user_id = user.id
        ) AS collection_count
      FROM
        users user
Run Code Online (Sandbox Code Playgroud)

所有 *_id 字段都已编入索引。使用解释(分析,详细)(删除敏感信息):

 Limit  (cost=0.00..156500.97 rows=100 width=41) (actual time=0.064..28345.363 rows=100 loops=1)
   Output: (...), ((SubPlan 1)), ((SubPlan 2))
   ->  Seq Scan on public.users user  (cost=0.00..14549429167.11 rows=9296702 width=41) (actual time=0.064..28345.241 rows=100 loops=1)
         Output: (...), (SubPlan 1), (SubPlan 2)
         SubPlan 1 …
Run Code Online (Sandbox Code Playgroud)

postgresql performance index count postgresql-performance

4
推荐指数
1
解决办法
3691
查看次数