IN 子句如何影响 oracle 的性能?
UPDATE table1
SET col1 = 'Y'
WHERE col2 in (select col2 from table2)
在上面的查询中,假设内部查询返回 10000 行。这个带有 IN 子句的查询会影响性能吗?
如果是这样,可以采取什么措施来加快执行速度?
UPDATE table1
SET col1 = 'Y'
WHERE col2 in (select col2 from table2)
In the above query, imagine the inner query returns 10000 rows. Does this query with IN clause affect performance?
If so, what can be done for faster execution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果子查询返回的行数与 TABLE1 中的行数相比,优化器可能会生成如下计划:
它将扫描两个表一次,并仅更新 TABLE1 中两个表共有的行。如果您需要更新大量行,这是一个高效的计划。
有时,与 TABLE1 中的行数相比,内部查询的行数很少。如果您在
TABLE1(col2)
上有索引,则可以获得与此类似的计划:在这种情况下,Oracle 将从 TABLE2 中读取行,并对每个(唯一)行执行索引访问表 1。
哪种访问速度更快取决于内部查询的选择性和 TABLE1 上索引的聚类(TABLE1 中
col2
值相似的行是相邻的还是随机分布的?)。无论如何,从性能角度来看,如果您需要执行此更新,此查询是最快的方法之一。if the subquery returns a large number of rows compared to the number of rows in TABLE1, the optimizer will likely produce a plan like this:
It will scan both tables once and update only the rows in TABLE1 common to both tables. This is a highly efficient plan if you need to update lots of rows.
Sometimes the inner query will have few rows compared to the number of rows in TABLE1. If you have an index on
TABLE1(col2)
, you could then obtain a plan similar to this one:In that case Oracle will read the rows from TABLE2 and for each (unique) row, perform an index access on TABLE1.
Which access is faster depend upon the selectivity of the inner query and the clustering of the index on TABLE1 (are the rows with similar value of
col2
in TABLE1 next to each other or randomly spread?). In any case, performance wise, if you need to perform this update this query is one of the fastest way to do it.这可能会更好
要了解哪个更好 - 查看执行计划。
This could be better
To get the idea which is better - look at the execution plan.
来自甲骨文:
根据我的经验,我看到使用 EXISTS 的更好计划,其中子查询返回大量行。
有关 Oracle 的更多讨论,请参阅此处
From Oracle:
From my experience, I have seen better plans using EXISTS where subquery returns large amount of rows.
See here for more discussion from Oracle