丝绸之路传奇方卫国:SQL语句的问题,关于SELECT

来源:百度文库 编辑:高考问答 时间:2024/04/27 02:56:49
以下是都是 ASP + SQL Server 环境下
关于排序方面的。要求是,
例如:假如查询条件为“abc”时(a,b,c各为一个查询字符串)
一、查询出同时包含a,b,c的行(意思是只要有一个行同时包含a,b,c,这三个字母之间的顺序无所谓)。
二、查询出只包含其中任意两个字母的行,(例如包含a和b,a和c,b和c)。
三、查询出只包含其中一个字母的行。

然后进行排序。
要求
同时包含abc三个的在最前面,
然后是只包含其中任意两个的
只包含其中一个的排在最后面,

总的意思就是,有多个查询字符串,包含所有字符串的行(如果有)排在最前面,然后是包含其中任意多个的,只包含其中一个的排在最后面
就像搜索引擎一样,最精确的符合条件的排列在最前面,不太精确的排在后面,即以符合条件的精确度排序。

如果给出完成方案,另有分,我很急啊,全部给您都可以!

假设你的表名为test,其中搜索的字段为text,表内容如下:

text
——————
about
out
where
this
come
isit
comeisit
isitko
kois

示例代码如下:

declare @a varchar(20),@b varchar(20),@c varchar(20) /*三个搜索条件*/

set @a = 'is'
set @b = 'it'
set @c = 'ko'

select *,IDENTITY(int,1,1) as id into #Temp from
(
select *,1 as lv from test where text like '%'+@a+'%' and text like '%'+@b+'%' and text like '%'+@c+'%'
union select *,2 as lv from test where (text like '%'+@a+'%' and text like '%'+@b+'%') or (text like '%'+@a+'%' and text like '%'+@c+'%') or (text like '%'+@b+'%' and text like '%'+@c+'%')
union select *,3 as lv from test where text like '%'+@a+'%' or text like '%'+@b+'%'or text like '%'+@c+'%'
) as tmp order by lv

select text from #Temp t1 where
id=(select min(id) from #Temp t2 where t1.text = t2.text) order by id

drop table #Temp

列出结果如下:

text
----------
isitko
comeisit
isit
kois
this

这样就满足了你的需求:满足更多条件的排序更靠上。

用包含就行了select * from 表 where xxx='%x%' and xxx='%y%'.....