相关疑难解决方法(0)

使用大 IN 优化 Postgres 查询

此查询获取您关注的人创建的帖子列表。您可以关注无限数量的人,但大多数人关注 < 1000 人。

使用这种查询方式,明显的优化是缓存"Post"id,但不幸的是我现在没有时间这样做。

EXPLAIN ANALYZE SELECT
    "Post"."id",
    "Post"."actionId",
    "Post"."commentCount",
    ...
FROM
    "Posts" AS "Post"
INNER JOIN "Users" AS "user" ON "Post"."userId" = "user"."id"
LEFT OUTER JOIN "ActivityLogs" AS "activityLog" ON "Post"."activityLogId" = "activityLog"."id"
LEFT OUTER JOIN "WeightLogs" AS "weightLog" ON "Post"."weightLogId" = "weightLog"."id"
LEFT OUTER JOIN "Workouts" AS "workout" ON "Post"."workoutId" = "workout"."id"
LEFT OUTER JOIN "WorkoutLogs" AS "workoutLog" ON "Post"."workoutLogId" = "workoutLog"."id"
LEFT OUTER JOIN "Workouts" AS "workoutLog.workout" ON "workoutLog"."workoutId" = "workoutLog.workout"."id"
WHERE
"Post"."userId" IN …
Run Code Online (Sandbox Code Playgroud)

postgresql performance index optimization postgresql-performance

51
推荐指数
2
解决办法
7万
查看次数

为读取性能配置 PostgreSQL

我们的系统写入了大量数据(一种大数据系统)。写入性能足以满足我们的需求,但读取性能真的太慢了​​。

我们所有表的主键(约束)结构都相似:

timestamp(Timestamp) ; index(smallint) ; key(integer).
Run Code Online (Sandbox Code Playgroud)

一个表可以有数百万行,甚至数十亿行,而一个读请求通常是针对特定时间段(时间戳/索引)和标记的。查询返回大约 20 万行是很常见的。目前,我们每秒可以读取大约 15k 行,但我们需要快 10 倍。这是可能的,如果是,如何?

注意: PostgreSQL 是和我们的软件一起打包的,所以不同客户端的硬件是不一样的。

它是一个用于测试的虚拟机。VM 的主机是具有 24.0 GB RAM 的 Windows Server 2008 R2 x64。

服务器规范(虚拟机 VMWare)

Server 2008 R2 x64
2.00 GB of memory
Intel Xeon W3520 @ 2.67GHz (2 cores)
Run Code Online (Sandbox Code Playgroud)

postgresql.conf 优化

shared_buffers = 512MB (default: 32MB)
effective_cache_size = 1024MB (default: 128MB)
checkpoint_segment = 32 (default: 3)
checkpoint_completion_target = 0.9 (default: 0.5)
default_statistics_target = 1000 (default: 100)
work_mem = 100MB (default: 1MB)
maintainance_work_mem = 256MB …
Run Code Online (Sandbox Code Playgroud)

postgresql performance postgresql-9.1 query-performance

47
推荐指数
2
解决办法
4万
查看次数

空间索引可以帮助“范围-排序-限制”查询吗

问这个问题,特别是针对 Postgres,因为它对 R 树/空间索引有很好的支持。

我们有下表,其中包含单词及其频率的树结构(嵌套集模型):

lexikon
-------
_id   integer  PRIMARY KEY
word  text
frequency integer
lset  integer  UNIQUE KEY
rset  integer  UNIQUE KEY
Run Code Online (Sandbox Code Playgroud)

和查询:

SELECT word
FROM lexikon
WHERE lset BETWEEN @Low AND @High
ORDER BY frequency DESC
LIMIT @N
Run Code Online (Sandbox Code Playgroud)

我认为覆盖索引(lset, frequency, word)会很有用,但我觉得如果范围内的lset值太多,它可能表现不佳(@High, @Low)

(frequency DESC)有时,当使用该索引的搜索早期产生@N与范围条件匹配的行时,一个简单的索引也可能就足够了。

但似乎性能在很大程度上取决于参数值。

有没有办法让它快速执行,不管范围(@Low, @High)是宽还是窄,也不管高频词是否幸运地在(窄)选择的范围内?

R-tree/空间索引有帮助吗?

添加索引,重写查询,重新设计表,没有限制。

postgresql performance index database-design query-performance

28
推荐指数
2
解决办法
4312
查看次数

为什么添加 LIMIT 200 会导致查询变慢?

我正在尝试调试 PostgreSQL 9.1.13 数据库上的慢查询,我有点不知所措。ORM 框架生成的确切查询是:

SELECT "core_product"."sales_price", "core_product"."recommended_price", "core_productgroup"."name", "core_product"."number", "core_product"."name", "core_product"."description", "core_product"."cost_price", "core_product"."bar_code", "core_product"."accessible"
FROM "core_product" INNER JOIN "core_productgroup" ON ( "core_product"."product_group_id" = "core_productgroup"."id" )
WHERE "core_productgroup"."company_id" = 1056
ORDER BY "core_product"."id" ASC
LIMIT 200;
Run Code Online (Sandbox Code Playgroud)

此查询需要 28 秒才能返回 200 行,这对于我们的用例来说太慢了。

首次尝试了解性能瓶颈可能在哪里。我首先尝试删除LIMIT 200预期它会更慢。但是没有LIMIT 200查询只需要 2 秒就返回大约 293000 行。

如何更快地返回所有 293000 个匹配行而不是仅返回前 200 行?

我尝试使用EXPLAIN查看两个查询的查询计划有何不同。事实证明,这两个几乎相同的查询具有完全不同的查询计划。与LIMIT

                                                   QUERY PLAN                                                   
----------------------------------------------------------------------------------------------------------------
 Limit  (cost=10.69..52229.70 rows=200 width=76)
   ->  Nested Loop  (cost=10.69..17054740.55 rows=65320 width=76)
         Join Filter: (core_product.product_group_id = core_productgroup.id) …
Run Code Online (Sandbox Code Playgroud)

postgresql

7
推荐指数
2
解决办法
4614
查看次数

在 ORDER BY 中使用 CASE .. END 有意义吗?

类似SELECT * FROM t ORDER BY case when _parameter='a' then column_a end, case when _parameter='b' then column_b end的查询是可能的,但是:这是一个好习惯吗?

在查询的 WHERE 部分使用参数是很常见的,在 SELECT 部分有一些计算列,但参数化 ORDER BY 子句并不常见。

假设我们有一个列出二手车的应用程序 (à la CraigsList)。汽车列表可以按价格或颜色排序。我们有一个函数,给定一定数量的参数(比如价格范围、颜色和排序标准),它会返回一组带有结果的记录。

为了具体起见,让我们假设cars都在下表中:

CREATE TABLE cars
(
  car_id serial NOT NULL PRIMARY KEY,  /* arbitrary anonymous key */
  make text NOT NULL,       /* unnormalized, for the sake of simplicity */
  model text NOT NULL,      /* unnormalized, for the sake of simplicity */
  year integer,             /* may …
Run Code Online (Sandbox Code Playgroud)

postgresql order-by dynamic-sql functions postgresql-9.6

6
推荐指数
1
解决办法
9741
查看次数

如何通过许多重复的 UNION 子查询来减少查询大小?

我使用 Postgres 13 并使用以下 DDL 定义了一个表:

CREATE TABLE item_codes (
    code    bytea                    NOT NULL,
    item_id bytea                    NOT NULL,
    time    TIMESTAMP WITH TIME ZONE NOT NULL,
    PRIMARY KEY (item_id, code)
);

CREATE INDEX ON item_codes (code, time, item_id);
Run Code Online (Sandbox Code Playgroud)

我使用以下查询:

SELECT DISTINCT time, item_id
FROM (
      (SELECT time, item_id
       FROM item_codes
       WHERE code = '\x3965623166306238383033393437613338373162313934383034366139653239'
       ORDER BY time, item_id
       LIMIT 100)
       UNION ALL
      (SELECT time, item_id
       FROM item_codes
       WHERE code = '\x3836653432356638366638636338393364373935343938303233343363373561'
       ORDER BY time, item_id
       LIMIT 100)
     ) AS items
ORDER …
Run Code Online (Sandbox Code Playgroud)

postgresql execution-plan union query-performance postgresql-performance

6
推荐指数
1
解决办法
608
查看次数

在具有小 LIMIT 的外部查询中添加 ORDER BY 时,复杂视图会变慢

我在视图中有一个非常大的查询(让我们称之为a_sql),这真的很快,除非我ORDER BYSELECT带有小的外部使用LIMIT

SELECT
customs.id AS custom_id, customs.custom_name AS custom_name, customs.slug AS slug, customs.use_case AS custom_use_case,
SUM(CASE WHEN designers.id = orders.user_id AND orders.bulk = 't' THEN order_rows.quantity ELSE 0 END) AS sale_bulk,
SUM(CASE WHEN designers.id = orders.user_id AND orders.bulk = 'f' THEN order_rows.quantity ELSE 0 END) AS sale_not_bulk,
SUM(CASE WHEN designers.id = orders.user_id THEN order_rows.quantity ELSE 0 END) AS sale_total,
SUM(CASE WHEN designers.id <> orders.user_id AND orders.bulk = 't' THEN order_rows.quantity ELSE 0 …
Run Code Online (Sandbox Code Playgroud)

postgresql performance optimization view postgresql-9.4 postgresql-performance

2
推荐指数
2
解决办法
1457
查看次数

PostgreSQL 查询性能因 WHERE 子句值而异

根据user_id我在子句中使用的查询,我遇到了性能问题WHERE

这个问题描述了一个非常相似的问题,但不完全相同:

这是我的查询:

select inlineview.user_search_id, inlineview.user_id, 
       to_char(timezone('UTC', to_timestamp(date_part('epoch', 
       inlineview.last_access_date))),'YYYY-MM-DD"T"HH24:MI:SS.MSZ') 
       last_access_date,
       to_char(timezone('UTC', to_timestamp(date_part('epoch', 
       inlineview.sys_creation_date))),'YYYY-MM-DD"T"HH24:MI:SS.MSZ') 
       sys_creation_date, b.product_id,
       to_char(timezone('UTC', to_timestamp(date_part('epoch', 
       b.last_prov_change))),'YYYY-MM-DD"T"HH24:MI:SS.MSZ') 
      last_prov_change,b.product_type,b.tlc_id,b.prod_history_id,
      coalesce(d.address_id,-1) address_id,coalesce(d.locality_name,'') 
      locality_name,
      coalesce(d.post_code_zone,'') post_code_zone,
      coalesce(d.road_name_concat,'') 
      road_name_concat,coalesce(d.street_num_concat,'') street_num_concat,
      coalesce(d.address_name,'') address_name,
      coalesce(d.town_name,'') town_name
from
    (select a.user_search_id, 
            a.user_id,a.last_access_date,
            a.sys_creation_date,a.product_id
     from linetest.user_search a
    where a.user_id = '818901'
    order by a.last_access_date desc limit 10) inlineview, 
 linetest.prod_history b left outer join linetest.address d on d.tlc_id = b.tlc_id 
 where b.product_id = inlineview.product_id
   and b.prod_history_id = (select c.prod_history_id 
                            from linetest.prod_history c
                            where …
Run Code Online (Sandbox Code Playgroud)

postgresql performance index execution-plan postgresql-performance

2
推荐指数
1
解决办法
1845
查看次数