两者中哪一个性能更好(最近有人指责我对我的代码不小心,因为我在 Oracle 中使用了后者):
Select *
from Tab1
Where (not) exists(Select 1 From Tab2 Where Tab1.id = Tab2.id)
Select *
from Tab1
Where (not) exists(Select Field1 From Tab2 Where Tab1.id = Tab2.id)
或者它们都是一样的吗?
请从 SQL Server 和 Oracle 的角度回答。
我用谷歌搜索(主要是从sql服务器端),发现对此仍然有很多争论,尽管我目前的观点/假设是RDMBS中的优化器足够成熟,可以理解从子查询是一个 bool 值。
最佳答案
是的,它们是相同的。 exists
检查子查询中是否至少有一行。如果是,则计算结果为 true
。子查询中的列无论如何都不重要。
根据MSDN ,存在
:
Specifies a subquery to test for the existence of rows.
和Oracle :
An EXISTS condition tests for existence of rows in a subquery.
也许是 MySQL documentation更能解释:
Traditionally, an EXISTS subquery starts with SELECT *, but it could begin with SELECT 5 or SELECT column1 or anything at all. MySQL ignores the SELECT list in such a subquery, so it makes no difference.
关于sql - 存在/不存在 : 'select 1' vs 'select field' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26461868/