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

求个sql语句!
一个字段varchar类型,里面保存的是另一张表的ID,不过存了多个用,隔开
1,2,3
21,32
13,24,32
这样的。
怎么查询包含某个id的数据呢
这样保存数据有点不科学啊

------解决方案--------------------
select * from tb 
where charindex(','+cast(id as varchar)+',',','+字段+',')>0

------解决方案--------------------
if OBJECT_ID('tempdb..#temp', 'u') is not null   drop table #temp;
go
create table #temp( [name] varchar(100));
insert #temp
select '1,2,3' union all
select '21,32' union all
select '13,24,32' 

--SQL:
SELECT a.rowid, b.[name]
FROM
(SELECT rowid=ROW_NUMBER() OVER(ORDER BY GETDATE()),[name]=CONVERT(XML, '<root><v>'+replace([name],',','</v><v>')+'</v></root>') FROM #temp) a
OUTER APPLY
(SELECT [name] = C.v.value('.','NVARCHAR(MAX)') FROM a.[name].nodes('/root/v') C(v)) b

/*
rowid name
1 1
1 2
1 3
2 21
2 32
3 13
3 24
3 32
*/

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

select * from 另外一个表 t1
where exists(select 1 from tb 
             where charindex(','+cast(id as varchar)+',',','+字段+',')>0)

------解决方案--------------------
这样容易理解:

select a.*
from ta a
inner join tb b on charindex(','+cast(a.id as varchar)+',',','+b.字段+',')>0