sql中的in转为 exists 语句

来源:百度知道 编辑:UC知道 时间:2024/05/14 01:34:29
原始sql语句:select * from t where id in (1,2,3,4,5)
如何将此语句转为exists ,也就是说用exists 来实现。

exists是必须用在两个select之间的 所以IN转换成exists时 必须把条件用另外一个select的形式表达出来

借用1楼的语句
select *
from t as T
where not exists(( select t.id
from t
where t.id=T.id)
except
(select *
from (1,2,3,4,5)
))
如果想要搞清楚exists与In的区别可以在联机丛书中输入exists里面讲得很详细

除非in里面的取另一个表的数据,可用exists效率高

--可用between,是聚集索引是以下方式效率高
select * from t where id between 1 and 5

select *
from t as T
where not exists(( select t.id
from t
where t.id=T.id)
except
(select *
from (1,2,3,4,5)
))
思想:因为选的是id在(1,2,3,4,5)中的t中的元组,所以对每个id看成是一个单元素集合,减去(1,2,3,4,5)如果是空集就说明id 在之中。

没道理的改法,为什么非要用exists来实现呢,这个语句用exists来实现并不好

select * from t
where id exists (select * from tmp where tmp.id = t.id)

简化一下就是上面的句子,
tmp表用下面部分代替,