Postgresql 哪个查询更快?
我得到两个答案:。但我仍然不知道哪一个是有效的。下面是对这两个方面的解释: 解释Postgresql 哪个查询更快?,postgresql,query-optimization,sql-execution-plan,Postgresql,Query Optimization,Sql Execution Plan,我得到两个答案:。但我仍然不知道哪一个是有效的。下面是对这两个方面的解释: 解释my查询: Hash Anti Join (cost=136.09..138.49 rows=1 width=556) Hash Cond: (t1.id = t2.parent_id) CTE tree -> Recursive Union (cost=0.14..132.81 rows=101 width=556) -> Index Scan us
my
查询:
Hash Anti Join (cost=136.09..138.49 rows=1 width=556)
Hash Cond: (t1.id = t2.parent_id)
CTE tree
-> Recursive Union (cost=0.14..132.81 rows=101 width=556)
-> Index Scan using resource_type_idx_parent_resource_type_id on resource_type (cost=0
Index Cond: (parent_resource_type_id IS NULL)
-> Hash Join (cost=0.33..12.26 rows=10 width=556)
Hash Cond: (rt.parent_resource_type_id = tree.id)
-> Seq Scan on resource_type rt (cost=0.00..11.30 rows=130 width=524)
-> Hash (cost=0.20..0.20 rows=10 width=36)
-> WorkTable Scan on tree (cost=0.00..0.20 rows=10 width=36)
-> CTE Scan on tree t1 (cost=0.00..2.02 rows=101 width=556)
-> Hash (cost=2.02..2.02 rows=101 width=4)
-> CTE Scan on tree t2 (cost=0.00..2.02 rows=101 width=4)
Laurenz-Albe
回答:
Nested Loop Anti Join (cost=132.81..388.39 rows=100 width=556)
Join Filter: (t2.deep_name ~~ (t1.deep_name || '.%'::text))
CTE tree
-> Recursive Union (cost=0.14..132.81 rows=101 width=556)
-> Index Scan using resource_type_idx_parent_resource_type_id on resource_type (cost=0
Index Cond: (parent_resource_type_id IS NULL)
-> Hash Join (cost=0.33..12.26 rows=10 width=556)
Hash Cond: (rt.parent_resource_type_id = tree.id)
-> Seq Scan on resource_type rt (cost=0.00..11.30 rows=130 width=524)
-> Hash (cost=0.20..0.20 rows=10 width=36)
-> WorkTable Scan on tree (cost=0.00..0.20 rows=10 width=36)
-> CTE Scan on tree t1 (cost=0.00..2.02 rows=101 width=556)
-> CTE Scan on tree t2 (cost=0.00..2.02 rows=101 width=32)
区别在于:
--- CTE Scan on tree (cost=132.81..134.83 rows=101 w (Selection)
+++ (clipboard)
@@ -1,5 +1,5 @@
- Hash Anti Join (cost=136.09..138.49 rows=1 width=556)
- Hash Cond: (t1.id = t2.parent_id)
+ Nested Loop Anti Join (cost=132.81..388.39 rows=100 width=556)
+ Join Filter: (t2.deep_name ~~ (t1.deep_name || '.%'::text))
CTE tree
-> Recursive Union (cost=0.14..132.81 rows=101 width=556)
-> Index Scan using resource_type_idx_parent_resource_type_id on resource_type (cost=0
@@ -10,5 +10,4 @@
-> Hash (cost=0.20..0.20 rows=10 width=36)
-> WorkTable Scan on tree (cost=0.00..0.20 rows=10 width=36)
-> CTE Scan on tree t1 (cost=0.00..2.02 rows=101 width=556)
- -> Hash (cost=2.02..2.02 rows=101 width=4)
- -> CTE Scan on tree t2 (cost=0.00..2.02 rows=101 width=4)
+ -> CTE Scan on tree t2 (cost=0.00..2.02 rows=101 width=32)
哪一个更快?如何从解释结果中知道这一点?在这两种方法上运行
explain(ANALYZE,BUFFERS)
。差异(如果有)并不显著。CTE只产生100行,并且(反)自连接可以完全在内存中执行。缝合缓冲区。顺便说一句:CTE和~~运算符都可能导致非平凡数据量的降级。EXPLAIN ANALYZE
是您的朋友。在我看来,第一个版本的Hash-Anti-join略优于嵌套循环。