坏(相关)或好(不相关)子查询? [英] Bad (correlated) or Good (not correlated) subquery?

查看:54
本文介绍了坏(相关)或好(不相关)子查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,下面更新语句中的子查询是好(不相关)还是坏(子查询)?

I wonder, if the subquery in the following update statement is a good (not correlated) or bad (subquery)?

换句话说,我的问题是,这是一个低效的查询吗?

In other words, my question is, is it an inefficient query?

UPDATE tableA
SET field1=0
FROM tableA
WHERE field2 IN (SELECT field2 
                 FROM tableA
                 WHERE someField IS NOT NULL 
                 AND someOtherField = 'ABC')

推荐答案

您的查询没有关联,它只是一个子查询..

Your query is not correlated ,its just a subquery..

下面是一个相关的子查询..

below is a correlated subquery..

UPDATE a
SET field1=0
FROM tableA a
WHERE exists  (SELECT 1
                 FROM tableB b
                 WHERE a.somecol=b.somecol)

相关子查询的另一个例子

one more example of correlated subquery

select orderid,
(select custname from customers c where c.custid=o.custid) from orders o

上面的查询可以写成join

above query can be written as join

select orderid,custname
 from orders o
 join
 customers c
 on c.custid=o.custid

执行两个查询往往使用相同的执行计划,并且两者的成本也相同..所以我们不能假设,相关的子查询不会表现得更好

executing both queries tend to use same execution plan and both have same cost as well..so we can't assume,Correlated subqueries won't perform better

select orderid,
(select count(orderid) from orders o2 where o2.custid=o.custid ) 
from orders o

对于上述相关子查询,SQL 不能只访问一次订单表并进行所有计算,它需要访问表两次..这只是我在相关子查询中看到的问题

for the above correlated subquery,SQL can't access orders table only once and do all the calculations,it will need to access table twice..this is only gotcha i could see with correlated subqueries

这篇关于坏(相关)或好(不相关)子查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆