+ -
当前位置:首页 → 问答吧 → like 模糊查询语句

like 模糊查询语句

时间:2011-12-15

来源:互联网

表A有 中字段 title(标题) ,tags(关键字,多个关键字用,逗号隔开)

现在进行关键字查询 先进行所有的 tags 匹配,如果没有再进行 title匹配,要求 有tags关键字匹配 排在前面,然后再排title匹配的

作者: tianlebest   发布时间: 2011-12-15

order by case when charindex(','+titile+',',','+关键字+',')>0 then 1 else 0 end

作者: fredrickhu   发布时间: 2011-12-15

貌似需要把关键字拆分开来比较啊

作者: ssp2009   发布时间: 2011-12-15

以查找"vbn"为例

SQL code

create table t1 (title varchar(10),tags varchar(20))
insert t1
select 'abc','zxc,vbn,qwer' union all
select 'vbn','tyu,uio,vbn' union all
select 'vbn','tyu,uio,vbn' union all
select 'abc','abc,vbn,tyu' union all
select 'vbn','tyu,uio' union all
select 'vbn',null union all
select null,'vbn'
go

select * from t1
-- where
-- tags like '%vbn%'
-- or
-- title like '%vbn%'
order by 
(case when charindex(','+tags+',',',vbn,')>0 then 0 
      when tags is null then 2
      else 1
      end
)

/*
(所影响的行数为 7 行)
title    tags
-----  -------
NULL    vbn
abc    zxc,vbn,qwer
vbn    tyu,uio,vbn
vbn    tyu,uio,vbn
abc    abc,vbn,tyu
vbn    tyu,uio
vbn    NULL
*/
go
drop table t1


是这样吗?
多条件排序,我也很混乱...

作者: xiaolinyouni   发布时间: 2011-12-15