Tur*_*hin 2 sql postgresql common-table-expression postgresql-performance
我有一个(可能)基本问题,关于Postgres如何执行包含WITH子句的查询.我想知道在WITH子句中包含多余的表是否会减慢查询速度.也就是说,如果在WITH子句中创建的"临时"表永远不会在子句之外调用WITH,那么实际创建的是"临时"表吗?
在第一个例子中,我正在加入两个使用WITH子句创建的"临时"表:
--Example 1
WITH temp1 as (
SELECT * from table_1
),
temp2 as (
select * from table_2
)
select *
from temp1
join temp2;
Run Code Online (Sandbox Code Playgroud)
在第二个例子中,我正在执行完全相同的查询,除了在WITH子句中创建了一个无关的表"temp3" .
--Example 2
WITH temp1 as (
SELECT * from table_1
),
temp2 as (
select * from table_2
),
temp3 as (
select * from table_3
)
select *
from temp1
join temp2;
Run Code Online (Sandbox Code Playgroud)
这两个查询之间有任何性能差异吗?如果table_3是一个巨大的表,这会减慢示例2与示例1中的查询吗?如果没有,为什么不呢?
好像它不会影响查询时间.我仍然很好奇为什么,尽管......
您可以使用Explain来显示查询优化器将如何处理您的查询.
http://www.postgresql.org/docs/9.2/static/sql-explain.html
在上面的情况下,PSQL应该看到temp3没有被使用而且不包括它.
在我的dbs上使用上面的例子.
explain with temp1 as (select * from cidrs), temp2 as (select * from contacts), temp3 as ( select * from accounts ) select * from temp1 join temp2 on temp1.id = temp2.id;
QUERY PLAN
---------------------------------------------------------------------
Hash Join (cost=22.15..25.44 rows=20 width=4174)
Hash Cond: (temp1.id = temp2.id)
CTE temp1
-> Seq Scan on cidrs (cost=0.00..11.30 rows=130 width=588)
CTE temp2
-> Seq Scan on contacts (cost=0.00..10.20 rows=20 width=3586)
-> CTE Scan on temp1 (cost=0.00..2.60 rows=130 width=588)
-> Hash (cost=0.40..0.40 rows=20 width=3586)
-> CTE Scan on temp2 (cost=0.00..0.40 rows=20 width=3586)
(9 rows)
Run Code Online (Sandbox Code Playgroud)
你会注意到没有提到temp3.在回答您的编辑时,关于它为什么不影响查询时间,优化器足够聪明,可以看到它没有被使用,也不会打扰它.因此它是优化器的原因.
你已经从@Doon那里得到了主要答案。
由于您对性能感兴趣,请注意,在大多数情况下,子查询通常比CTE 快。通用表表达式(WITH 查询)构成优化障碍。有关详细信息,请阅读有关 pgsql-performance 的此线程。
使用 CTE ...
| 归档时间: |
|
| 查看次数: |
2468 次 |
| 最近记录: |