加入多个常见的 table 表达式 (CTE) 在 SQL 中花费的时间太长(查询不会结束)我的代码有问题吗?

Joining more than one common table expression (CTE) is taking too long in SQL (query will not end) is there something wrong with my code?

我是 运行 一个包含两个连接的 CTE 的查询,然后是一个使用连接的 CTE 的查询。然而,这个查询昨天 运行 持续了几个小时,而且从未完成。我通常在一分钟内完成的查询。

这是我正在运行的查询:

WITH cte_second_try AS (
SELECT primary_key as timing,
MIN(timedate) AS second_try,
FROM table t1
WHERE timedate > (SELECT MIN(timedate) FROM table t2 WHERE t1.primary_key = t2.primary_key group by primary_key)
AND criteria1='x' AND timedate BETWEEN 'x' AND 'x' GROUP BY 1),

cte_timing AS (
SELECT MIN(timedate) AS first_try, MIN(second_try) AS second_try,
FROM table t3
LEFT JOIN cte_second_try ON t3.primary_key = cte_second_try.timing
WHERE criteria1='x' AND timedate BETWEEN 'x' AND 'x' group by 1)

SELECT id, t4.primary_key, var2, var3, var4, var5 etc
 CASE
 WHEN var2 <> 'string'
 THEN 0
 WHEN cte_timing.first_try = t4.timedate
 THEN 1
 WHEN cte_timing.second_try = t4.timedate
 THEN 2
 ELSE 3 END
FROM table t4
 LEFT JOIN cte_timing ON t4.primary_key = cte_timing.primary_key
WHERE criteria1='x' AND timedate BETWEEN 'x' AND 'x'
ORDER BY timedate;

对于导致此瓶颈的原因有什么建议吗?

此外,这是我第一次加入 CTE,所以我加入 CTE 的方式可能有问题。一般的想法是,我在第一个 CTE 中找到对任务的第二次尝试,在第二个 CTE 中找到对任务的第一次尝试,然后在最后的查询中通过第二个引用两者。

我正在使用 PostgreSQL

我有这个问题的答案。

我刚刚收到一位技术人员的回复,这是因为索引。

通过添加索引,查询成本从:

成本=151491121951.08 到 成本=820386.91

你可以这样做:

EXPLAIN SELECT primary_key as timing,
MIN(timedate) AS second_try,
FROM table t1
WHERE timedate > (SELECT MIN(timedate) FROM table t2 WHERE t1.primary_key = t2.primary_key group by primary_key)
AND criteria1='x' AND timedate BETWEEN 'x' AND 'x' GROUP BY 1

使用EXPLAIN

获取查询成本