SQL语句优化的小问在线急求

select *
from A where id in (1,2,3)
怎么用exists 替代

数据库有优化机制,开发人员不需要对它优化

但是不是说in 语句要慢于exists吗?如果我in里面的内容非常多呢?怎么办

这里有sql中exists,not exists的用法,你看看吧
http://www.cnblogs.com/mytechblog/articles/2105785.html

如果1,2,3这种直接传值的,用In就可以了

如果是in (select id from table)这种的
改成exist(select 1 from table where table.id=id)

select * from A a where exists (select 1 from A b where a.id = b.id and b.id = 1 or b.id = 2 or b.id = 3 )

如果象你这样的值为连续的, 应该改为:
select * from A where id between 1 and 3

如果你in中的值特别多而又不连续可以这样:
declare @t table(
id int
)
insert into @t (id) values( 1 )
insert into @t (id) values( 22 )
insert into @t (id) values( 3 )
……

select * from A where exists(
select 1 from @t B where a.id=b.id
)

如果你的id是从页面传过来的一连串的字符串“1,22,3,45”之类的, 可以用字符串分割函数先转为表变量再操作。

不过一般情况下, 也就是说数据量比较小时, 不需要多作处理的, 象你说的8个值, 就没有必要大动干戈。

达到了50以上, 可以考虑。 或者你自己也可以去测试这个临界点的个数到底是多少

如果象你这样的值为连续的, 应该改为:
select * from A where id between 1 and 3

如果你in中的值特别多而又不连续可以这样:
declare @t table(
id int
)
insert into @t (id) values( 1 )
insert into @t (id) values( 22 )
insert into @t (id) values( 3 )
……

select * from A where exists(
select 1 from @t B where a.id=b.id
)

如果你的id是从页面传过来的一连串的字符串“1,22,3,45”之类的, 可以用字符串分割函数先转为表变量再操作。

不过一般情况下, 也就是说数据量比较小时, 不需要多作处理的, 象你说的8个值, 就没有必要大动干戈。

达到了50以上, 可以考虑。 或者你自己也可以去测试这个临界点的个数到底是多少

这个应该没办法用exists 替代

select *
from A where id in (1,2,3)
怎么用exists 替代

你可以把1,2,3放到一个表T的ID中,然后就可以写了
select * from A where exists (select 1 from T where id = A.id)
或者这样也行

select * from A where exists (select 1 from (select 'A' ID from dual union all select 'B' from dual union all select 'C' from dual) T
where id = A.id)