求个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
/*
rowidname
11
12
13
221
232
313
324
332
*/
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