sql - 在 WITH 子句中添加无关的表会减慢 PostgreSQL 中的查询速度吗?

标签 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;

在第二个示例中,我正在执行完全相同的查询,只是在 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;

这两个查询之间有什么性能差异吗?如果 table_3 是一个巨大的表,这会减慢示例 2 与示例 1 中的查询速度吗?如果不是,为什么不呢?

它似乎不会影响查询时间。不过我还是很好奇为什么...

最佳答案

您可以使用 Explain 来展示查询优化器将如何处理您的查询。

http://www.postgresql.org/docs/9.2/static/sql-explain.html

在上面的例子中,PSQL 应该看到 temp3 没有被使用并且不包含它。

在我的数据库上使用上面的示例。

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)

您会注意到没有提及 temp3。在回答您的编辑时,关于为什么它不影响查询时间,优化器足够聪明,可以看到它没有被使用并且不会打扰计算它。因此它是优化器的原因。

关于sql - 在 WITH 子句中添加无关的表会减慢 PostgreSQL 中的查询速度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20842936/

相关文章:

mysql - 删除可选查询 datagridview 中的冗余列

mysql - 在mysql中将varchar转换为二进制?

SQL 服务器 : how to find the record where a field is X for the first time and there are no later records where it isn't

sql - 如何识别特定时间范围内发生的行?

sql - 将 Excel 'if' 函数转换为 SQL 查询

sql - 插入时 float 更改为科学记数法

sql - PostgreSQL - 使用来自同一查询的先前计算值

sql - 在多个连接表上聚合函数

postgresql - Npgsql 或您的 PostgreSQL 不支持类型 System.UInt32

sql - 为什么 SQLite CTE JOIN 中的 RANDOM() 行为与其他 RDBMS 不同?