小编tur*_*nip的帖子

为什么 Postgres CTE 比子查询慢?

我有一个有点复杂的查询,它拆分字符串并将每个单词作为记录输出。

我做了一个快速测试,一个有 CTE,一个有子查询,看到 CTE 的执行时间是原来的两倍,我有点惊讶。

以下是查询功能的要点:

-- 1. translate matches characters from comment to given list (of symbols) and replaces them with commas.
-- 2. string_to_array splits string by comma and puts in an array
-- 3. unnest unpacks the array into rows
Run Code Online (Sandbox Code Playgroud)

内联子查询

SELECT
    sub_query.word,
    sub_query._created_at
FROM 
(   SELECT unnest(string_to_array(translate(nps_reports.comment::text, ' ,.<>?/;:@#~[{]}=+-_)("*&^%$£!`\|}'::text, ',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,'::text), ','::text, ''::text)) AS word,
        nps_reports.comment,
        nps_reports._id,
        nps_reports._created_at
    FROM nps_reports
    WHERE nps_reports.comment::text <> 'undefined'::text
) sub_query 
WHERE sub_query.word IS NOT NULL AND NOT (sub_query.word IN ( SELECT …
Run Code Online (Sandbox Code Playgroud)

postgresql performance cte query-performance

5
推荐指数
1
解决办法
5222
查看次数

标签 统计

cte ×1

performance ×1

postgresql ×1

query-performance ×1