用什么方法可以代替ID IN
本帖最后由 Mapleleaf123 于 2013-12-30 18:51:59 编辑 表1
id uid idlist
1 10 3,5,7,9,12,30
表2
id title
1 a
2 b
3 c
4 d
......
要取出uid=10的表2记录,现在是用select * from [表2] where id in (select idlist from [表1] where uid=10)
因为表1数据太多,这个有点慢,因为表1是早设计的
如果是现在的话,会考虑
表1
id uid idlist
1 10 5
2 10 7
3 10 3
。。。。。
这样的话可以先读表1再找表2应该会快好多
现在是想在不改变表1的情况下,有什么好的方法吗?
[解决办法]
把id放入表中,然后join,表可以是表变量,临时表等
[解决办法]
create table 表1(id int,uid int,idlist varchar(30))
insert into 表1
select 1 , 10 ,'3,5,7,9,12,30'
create table 表2(id int, title varchar(20))
insert into 表2
select 1, 'a' union all
select 2, 'b' union all
select 3, 'c' union all
select 4, 'd'
go
if OBJECT_ID('tempdb..#temp') is not null
drop table #temp
select *,
SUBSTRING(t.idlist, number ,CHARINDEX(',',t.idlist+',',number)-number) as v
into #temp
from 表1 t,master..spt_values s
where s.number >=1
and s.type = 'P'
and SUBSTRING(','+t.idlist,s.number,1) = ','
and t.uid = 10
select * from [表2] a
where exists (select idlist from #temp b where a.id = b.v)
/*
idtitle
3c
*/
create table t1(id int,uid int,idlist varchar(100))
insert into t1
select 1,10,'3,5,7,9,12,30'
create table t2(id int,title varchar(100))
insert into t2
select 1 ,'a'
union all select 2 ,'b'
union all select 3 ,'c'
union all select 4 ,'d'
select t2.*
from t2,t1
where t1.uid=10
and CHARINDEX(','+convert(varchar(100),t2.id)+',',','+t1.idlist+',')>0
create table 表1
(id int,uid int,idlist varchar(50))
insert into 表1
select 1,10,'3,5,7,9,12,30'
create table 表2
(id int,title varchar(10))
insert into 表2
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d'
-- 在[表2].[id]列建索引.
create index ix_tab2_id on 表2(id)
-- 在[表1].[uid]列建索引.
create index ix_tab1_uid on 表1(uid)
-- 用动态SQL实现.
declare @tsql varchar(6000)
select @tsql=idlist
from 表1 where uid=10
select @tsql='select * from [表2] where id in ('+@tsql+')'
exec(@tsql)
/*
id title
----------- ----------
3 c
(1 row(s) affected)
*/
select *
from [表2] as a where exists(select 1 from [表1] where uid=10 and ','+idlist+',' like '%,'+rtrim(a.id)+',%' )