gpt4 book ai didi

postgresql - 为什么 union 与 "or"运算符的查询计划有很大差异

转载 作者:行者123 更新时间:2023-12-05 02:27:50 26 4
gpt4 key购买 nike

在执行以下两个查询时,我注意到查询计划存在严重差异。这是为什么?

select * from table1
where id = 'dummy' or id in (select id from table2 where id = 'dummy')

查询计划

Seq Scan on table1  (cost=8.30..49611.63 rows=254478 width=820) (actual time=535.477..557.431 rows=1 loops=1)
Filter: (((code)::text = 'dummy'::text) OR (hashed SubPlan 1))
Rows Removed by Filter: 510467
SubPlan 1
-> Index Scan using idx on table2 (cost=0.29..8.30 rows=1 width=8) (actual time=0.009..0.012 rows=0 loops=1)
Index Cond: ((id)::text = 'dummy'::text)
Planning Time: 0.165 ms
Execution Time: 557.517 ms
select * from table1
where id = 'dummy'
union
select * from table1
where id in (select id from table2 where id = 'dummy')
Unique  (cost=25.22..25.42 rows=2 width=5818) (actual time=0.045..0.047 rows=1 loops=1)
-> Sort (cost=25.22..25.23 rows=2 width=5818) (actual time=0.045..0.046 rows=1 loops=1)
Sort Method: quicksort Memory: 25kB
-> Append (cost=0.42..25.21 rows=2 width=5818) (actual time=0.016..0.026 rows=1 loops=1)
-> Index Scan using id on table1 (cost=0.42..8.44 rows=1 width=820) (actual time=0.015..0.016 rows=1 loops=1)
Index Cond: ((id)::text = 'dummy'::text)
-> Nested Loop (cost=0.71..16.74 rows=1 width=820) (actual time=0.009..0.009 rows=0 loops=1)
-> Index Scan using idx on table2 (cost=0.29..8.30 rows=1 width=8) (actual time=0.008..0.008 rows=0 loops=1)
Index Cond: ((id)::text = 'dummy'::text)
-> Index Scan using pkey on table1 (cost=0.42..8.44 rows=1 width=820) (never executed)
Index Cond: (id = table2.id)
Planning Time: 0.753 ms
Execution Time: 0.131 ms

所以您可以看到的主要区别是第一个查询返回 254478 行,而第二个查询只返回 2 行。这是为什么?

最佳答案

请再做一次测试——运行这两个查询——它们给出的结果是否与未经我更改的查询的结果相同?

 select * from table1
where table1.id = 'dummy' or
table1.id in (select table2.id from table2 where table2.id = 'dummy')


select * from table1
where table1.id = 'dummy'
union
select * from table1
where table1.id in (select table2.id from table2 where table2.id = 'dummy')

我不认为您是在与我们分享您的实际代码——因为您编写的代码毫无意义——您在子查询中返回一个等于“dummy”的 ID 列表——所以您将只需多次获取虚拟列表即可。


请注意这些评论是不正确的,因为它们对结果没有影响——操作顺序按预期工作

这样做会得到什么结果:

select * from table1
where (id = 'dummy') or id in (select id from table2 where id = 'dummy')

您的查询给出更多结果的原因是因为它从表 1 中选择记录,其中 id 等于 dummy 或 id = id。原始帖子中的查询为您提供了所有记录。 OR 应用于第一个表达式而不拆分两个表达式。

关于postgresql - 为什么 union 与 "or"运算符的查询计划有很大差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72887103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com