关于分类多选,如何查询某个分类的信息,求SQL句子
记录某字段存储了当前记录的分类信息,如
blog_cateid=1,11,13,133
如何查找某个分类下的所有记录。?
比如现在查找分类ID为3的记录?
SQL句子如何写?
谢谢。
-------------------------------
我现在是这样使用的
select company_name... from databasetable where blog_cateid like '%3%'
这样做法如果是数量小还满过的去,但我现在实际情况是每个分类下都有可能有几十万的数据,这样查询的速度就太慢,不知道还有没别的办法解决这速度查询问题,还是这样类别多选择就这一方法解决
[解决办法]
拆分方法见下,不过LZ几十万在一行,拆出来的效率,真不会太高啊...
--参考拆分表:--> --> (Roy)生成測試數據 if not object_id('Tab') is null drop table TabGoCreate table Tab([Col1] int,[COl2] nvarchar(5))Insert Tabselect 1,N'a,b,c' union allselect 2,N'd,e' union allselect 3,N'f'Go--SQL2000用辅助表:if object_id('Tempdb..#Num') is not null drop table #Numgoselect top 100 ID=Identity(int,1,1) into #Num from syscolumns a,syscolumns bSelect a.Col1,COl2=substring(a.Col2,b.ID,charindex(',',a.Col2+',',b.ID)-b.ID) from Tab a,#Num bwhere charindex(',',','+a.Col2,b.ID)=b.ID --也可用 substring(','+a.COl2,b.ID,1)=','--2000不使用辅助表Select a.Col1,COl2=substring(a.Col2,b.number,charindex(',',a.Col2+',',b.number)-b.number) from Tab a join master..spt_values b ON B.type='p' AND B.number BETWEEN 1 AND LEN(A.col2)where substring(','+a.COl2,b.number,1)=','SQL2005用Xml:select a.COl1,b.Col2from (select Col1,COl2=convert(xml,'<root><v>'+replace(COl2,',','</v><v>')+'</v></root>') from Tab)aouter apply (select Col2=C.v.value('.','nvarchar(100)') from a.COl2.nodes('/root/v')C(v))bSQL05用CTE:;with roy as (select Col1,COl2=cast(left(Col2,charindex(',',Col2+',')-1) as nvarchar(100)),Split=cast(stuff(COl2+',',1,charindex(',',Col2+','),'') as nvarchar(100)) from Tabunion allselect Col1,COl2=cast(left(Split,charindex(',',Split)-1) as nvarchar(100)),Split= cast(stuff(Split,1,charindex(',',Split),'') as nvarchar(100)) from Roy where split>'')select COl1,COl2 from roy order by COl1 option (MAXRECURSION 0)生成结果:/*Col1 COl2----------- -----1 a1 b1 c2 d2 e3 f*/
[解决办法]
select company_name... from databasetable where blog_cateid like '3%'
like左边不加%,可以再建个索引提速
[解决办法]
try:select company_name... from databasetable where charindex(‘,’+ltrim(3),blog_cateid)>0