带子查询和不带子查询比较的SQL查询
我希望有人能解释一下这两个问题之间的逻辑区别。也许你也可以解释性能差异。(DB是Microsoft Northwind) --加入 --子查询带子查询和不带子查询比较的SQL查询,sql,sql-server,sql-server-2014,Sql,Sql Server,Sql Server 2014,我希望有人能解释一下这两个问题之间的逻辑区别。也许你也可以解释性能差异。(DB是Microsoft Northwind) --加入 --子查询 select customerid, companyname, contactname, country from customers where customerid in (select distinct customerid from orders) 提前感谢。第一个生成一个包含所有客户的所有订单的中间结果集。然后使用选择distinct减少它们
select customerid, companyname, contactname, country from customers
where customerid in (select distinct customerid from orders)
提前感谢。第一个生成一个包含所有客户的所有订单的中间结果集。然后使用
选择distinct
减少它们
第二种方法只是选择客户,以后不必减少客户数量。它应该更有效率。但是,子查询中不需要select distinct
(它是通过中的自动完成的)
我将把逻辑写成:
select c.customerid, c.companyname, c.contactname, c.country
from customers c
where exists (select 1
from orders o
where o.customerid = c.customerid
);
这可以很容易地利用订单(customerid)
上的索引,非常感谢。既然我是一个初学者,我对你的问题有怀疑,我的朋友。请您解释一下在您的查询中“存在”和“选择1”(真值返回?)的角色好吗?我不知道子查询是不同的,谢谢您的提示!天哪……不。后一个查询并不是一个真正的改进,ON操作符执行相同的过滤,实际上要好得多。首先,对于返回的每一行,谓词的计算结果必须为true。这意味着select查询实际上被激发了很多次。@clifton\u h。是时候学习数据库如何工作以及半联接运算符是什么了。@Gordon.Linoff遗憾的是,您似乎不理解外部应用运算符和基于集合的联接之间的区别。它可以…更好地取决于覆盖索引…它们不一样。
select c.customerid, c.companyname, c.contactname, c.country
from customers c
where exists (select 1
from orders o
where o.customerid = c.customerid
);