日期:2014-05-17  浏览次数:20476 次

用什么方法可以代替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)
/*
id title
3 c
*/

------解决方案--------------------

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