日期:2014-05-18  浏览次数:20583 次

sql 疑难查询语句
例如 这是张表 数据和类型都写出来了
table a
no(int) type(varchar(20)) 
5220 54,85
5220 60
4614 65,85,33
6835 12,16

现在需要从a表中
查到no=5220,type=85或type=60的那某数据数据  
因为type是varchar型 所以no=5220,type中含有85或60的也行 
只要取到按条件查的那行数据都行

sql语句怎么写

主要是因为type是varchar型 所以不能用type in(85,60)
这下该怎么写sql

------解决方案--------------------
探讨
select * from a where no 5220 and (','+type+',' like ',85,' or ','+type+',' like ',60,')

select * from a where no 5220 and (charindex(',85,' , ','+type+',') > 0 or charindex(',60,' , ','+type+',') ……

------解决方案--------------------
SQL code
create table a
(no int,type varchar(20))
go

insert into a
select 5220, '54,85' union all
select 5220, '60' union all
select 4614, '65,85,33' union all
select 6835 ,'12,16'
go
select * from (
select a.no ,
substring(','+a.type,b.number+1,charindex(',',a.type+',',b.number)-b.number) 'TYPE'
from  a
inner join master.dbo.spt_values b
on b.[type]='P' and 
substring(','+a.type,b.number,1)=',')as a where type='85' or type='60'