我刚刚学会(昨天)使用“exists”而不是“in”。
BAD
select * from table where nameid in (
select nameid from othertable where otherdesc = 'SomeDesc' )
GOOD
select * from table t where exists (
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeDesc' )
我对此有一些疑问:
1)我理解的解释是:“之所以更好,是因为只会返回匹配的值,而不是构建大量可能的结果”。这是否意味着虽然第一个子查询可能返回 900 个结果,第二个将只返回 1 个(是或否)?
2)过去我曾让 RDBMS 提示:“只能检索前 1000 行”,这第二种方法可以解决这个问题吗?
3)第二个子查询中别名的范围是什么?...别名是否只存在于括号中?
例如
select * from table t where exists (
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeDesc' )
AND
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeOtherDesc' )
也就是说,如果我使用相同的别名(o 表示其他表)在第二个“存在”中它会与第一个存在有什么问题吗?还是他们完全独立?
这是仅与 Oracle 相关的内容还是对大多数 RDBMS 有效?
非常感谢
最佳答案
它特定于每个 DBMS 并取决于查询优化器。一些优化器检测 IN 子句并翻译它。
在我测试的所有 DBMS 中,别名仅在 ( )
顺便说一句,您可以将查询重写为:
select t.*
from table t
join othertable o on t.nameid = o.nameid
and o.otherdesc in ('SomeDesc','SomeOtherDesc');
而且,回答你的问题:
关于SQL - 表别名范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/188828/