求助一条SQL语句:多关键词搜索
问题是这样的:
假设有一个表table1,其中有一个keyword列,该列存储的数据格式为“xxx|xxx|xxxx”关键词以竖线分割,数量不定,可能为空,也可能任意条数(通常不会超过3条)
现在的问题是该怎么写一条的SQL语句来搜索数据库,想实现的SQL语句如下:
rs.open "SELECT * FROM table1 WHERE (Title LIKE 'xxx' or Title LIKE 'xxx' or Title LIKE 'xxxx') and (ID <> "&Request("id")&") ORDER BY ID DESC",conn,1,1
该语句用于文章系统的相关文章列取。在线等,谢谢
问题点数:30、回复次数:5Top
1 楼sxycgxj(云中客)回复于 2005-04-03 17:53:15 得分 0
不明白什么意思Top
2 楼xluzhong(Ralph)回复于 2005-04-03 19:21:12 得分 0
rs.open "SELECT * FROM table1
WHERE charindex(title,keyword)>0
and (ID <> "&Request("id")&") ORDER BY ID DESC",conn,1,1Top
3 楼Initial_R(美女靠边)回复于 2005-04-04 12:35:01 得分 0
问题重述:
----------------------------------
表Table1
----------------------------------------------------------------
ID Keyword
1 游戏,传奇
2 科技
3 优惠,特价,点卡
----------------------------------------------------------------
通过设置数组智能搜索指定关键词,需要实现的语句如下。
rs.open "SELECT * FROM Table1 WHERE (Title LIKE '优惠' or Title LIKE '特价' or Title LIKE '点卡') and (ID <> "&Request("id")&") ORDER BY ID DESC",conn,1,1
Top
4 楼shiro(比卡丘)回复于 2005-04-12 17:49:04 得分 15
用charindex太过模糊了,建议使用PATINDEX
SELECT * FROM table1
WHERE ( PATINDEX('xxx|%',title)>0 or PATINDEX('%|xxx|%',title)>0 or PATINDEX('xxx',title)>0 )
and (ID <> "&Request("id")&") ORDER BY ID DESCTop
5 楼mschen(Co-ok)回复于 2005-04-12 18:58:17 得分 15
--写了一个函数来实现你说的功能.
--关键字表,它的id字段和文章表是一一对应的.当然也可以放在一起
create table tb_keywords(id int,KeyWord varchar(100))
insert tb_keywords
select 1,'游戏,传奇'
union select 2,'科技'
union select 3,'优惠,特价,点卡'
--文章表,存放文章的信息.
create table tb_article(id int,title varchar(100))
insert tb_article
select 1,'玩游戏的朋友'
union select 2,'新游戏'
union select 3,'点卡优惠'
union select 4,'高科技'
union select 5,'物理'
/* ******************************
函数功能:传入文章id和关键字,返回
存在这个关键字的文章列表.
*/
create function dbo.SearchKeywords
(@id int,@keywords varchar(100))
returns @t table (id int,title varchar(100))
as
begin
declare @key varchar(100)
while (charindex(',',@keywords)>0)
begin
set @key=left(@keywords,charindex(',',@keywords)-1)
insert @t
select * from tb_article t
where title like '%'+@key+'%' and [id]<>@id
and not exists(select 1 from @t where [id]=t.[id])
set @keywords=stuff(@keywords,1,charindex(',',@keywords),'')
end
insert @t
select * from tb_article t
where title like '%'+@keywords+'%' and [id]<>@id
and not exists(select 1 from @t where [id]=t.[id])
return
end
--查询
select * from dbo.SearchKeywords(1,'游戏,传奇')
Top




