sql中的in转为 exists 语句

2025-05-21 23:40:56
推荐回答(5个)
回答(1):

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

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

(
select 1 as x
union select 2
union select 3
union select 4
union select 5
)

完整如下

select * from t
where id exists (select * from
(
select 1 as x
union select 2
union select 3
union select 4
union select 5
)tmp
where tmp.id = t.id)

回答(2):

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 在之中。

回答(3):

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里面讲得很详细

回答(4):

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

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

回答(5):

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