postgresql - 减少 postgresql 中的执行时间

标签 postgresql query-performance

我在这里附上了我的查询。执行时间为 60141 毫秒。我不知道我该怎么办。但我想在短时间内执行。现在我发布了我的分析和执行查询的输出。请对此提供帮助。

EXPLAIN (BUFFERS,ANALYZE) SELECT id 
FROM activitylog 
WHERE (url = '/staff/save/117' OR url = '/staff/create/117') 
AND timestamp > '1990-01-01 00:00:00' 
AND userid IN ( SELECT id 
                FROM users 
                WHERE companyid = ( SELECT companyid 
                                    FROM users 
                                    WHERE id='150' ) ) 
ORDER BY timestamp DESC

输出:

Sort  (cost=934879.83..934879.83 rows=1 width=12) (actual time=63918.947..63918.948 rows=4 loops=1)
    Sort Key: activitylog."timestamp"
    Sort Method: quicksort  Memory: 25kB
    Buffers: shared hit=168161 read=561433
    InitPlan 1 (returns $0)
    ->  Index Scan using "usersPrimary" on users users_1  (cost=0.14..8.16 rows=1 width=4) (actual time=0.005..0.005 rows=1 loops=1)
       Index Cond: (id = 150)
       Buffers: shared hit=2
    ->  Nested Loop  (cost=0.00..934871.66 rows=1 width=12) (actual time=63918.693..63918.917 rows=4 loops=1)
        Join Filter: (activitylog.userid = users.id)
        Rows Removed by Join Filter: 400
        Buffers: shared hit=168158 read=561433
    ->  Seq Scan on users  (cost=0.00..10.53 rows=25 width=4) (actual time=0.018..0.085 rows=101 loops=1)
        Filter: (companyid = $0)
        Rows Removed by Filter: 114
        Buffers: shared hit=10
    ->  Materialize  (cost=0.00..934860.39 rows=2 width=16) (actual time=120.024..632.858 rows=4 loops=101)
        Buffers: shared hit=168148 read=561433
    ->  Seq Scan on activitylog  (cost=0.00..934860.38 rows=2 width=16) (actual time=12122.376..63918.564 rows=4 loops=1)
        Filter: (("timestamp" > '2019-01-02 19:19:12.649837+00'::timestamp with time zone) AND (((url)::text = '/jobs/save/81924'::text) OR ((url)::text = '/jobs/create/81924'::text)))
        Rows Removed by Filter: 11935833
        Buffers: shared hit=168148 read=561433
    Planning time: 0.806 ms
    Execution time: 63919.748 ms

提前致谢。

最佳答案

试试这个,连接查询会增强索引和优化查询执行时间

SELECT id
FROM activitylog
WHERE url in ('/staff/save/117','/staff/create/117')
  AND TIMESTAMP > '1990-01-01 00:00:00'
  AND EXISTS 
    (SELECT 1
     FROM users AS u
     JOIN users ur ON ur.CompanyID = u.CompanyID
     WHERE ur.ID = '150'
       AND u.id = activitylog.userid)
ORDER BY TIMESTAMP DESC

关于postgresql - 减少 postgresql 中的执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53430590/

相关文章:

Mysql/Mysqli/PDO 性能 - 我打印的表或表的数量

SQL 组表按 "leading rows"没有 pl/sql

database - 为用户无缝地将数据库打包到应用程序中

sql - 将列的值与该列的平均值进行比较 SQL

postgresql - postgres - 使用主键时外部查询速度慢

Oracle 2 索引位于相同列但顺序不同

postgresql - 定义一个 psql C 函数给出一个列定义列表是函数返回 "record"所必需的

sql - 搜索多个表的顺序

mysql - 复合索引最左边列中的通配符是否意味着索引中的剩余列不用于索引查找(MySQL)?

MySQL 主键未在查询中使用