我正在编写这样的查询:
select * from myTable where X in (select X from Y) and XX in (select X from Y)
X 列和 XX 列的值必须位于同一查询的结果中:select X from Y
.
我认为这个查询被调用了两次,所以它毫无意义。还有其他选项可以更有效地编写此查询吗?也许是临时表?
实际上不,考虑到 myTable.X 和 myTable.YY 匹配的 X 可能不是来自同一行,没有更智能的方法来编写此代码(无需访问 Y 两次)。
作为替代方案,查询的 EXISTS 形式是
select *
from myTable A
where exists (select * from Y where A.X = Y.X)
and exists (select * from Y where A.XX = Y.X)
如果 Y 包含 X 值1,2,3,4,5
, and x.x = 2
and x.xx = 4
,它们都存在(在 Y 中的不同记录上),并且 myTable 中的记录应显示在输出中。
编辑:这个答案之前指出You could rewrite this using _EXISTS_ clauses which will work faster than _IN_
。 AS Martin 指出,事实并非如此(当然不适用于 SQL Server 2005 及更高版本)。查看链接
- http://explainextended.com/2009/06/16/in-vs-join-vs-exists/ http://explainextended.com/2009/06/16/in-vs-join-vs-exists/
- http://sqlinthewild.co.za/index.php/2009/08/17/exists-vs-in/ http://sqlinthewild.co.za/index.php/2009/08/17/exists-vs-in/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)