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

关于模糊搜索的优化问题(高手请进!!!!!!!!!)
我有一个表 table1 
表中有两个字段 title(标题) 和 content(内容)
我想对title和content进行模糊查询,实现这样一个效果

当我查询关键词“西瓜 土豆 青椒”时
应该如何组合 sql语句来实现如下的效果
包含有“西瓜 土豆 青椒”的记录排在搜索结果的前面
然后是包含有“西瓜 土豆”或者“土豆 青椒”或者“西瓜 青椒”的排在中间
最后只包含有“西瓜” 或者 “土豆” 或者 “青椒” 的记录排在后面

请问如何实现请高手支招,谢谢!!!!

------解决方案--------------------
--1.分三次查询,分别按顺序显示:

select text_title tt,...... from table_test 
where all_text like '%西瓜 土豆 青椒%';

select text_title tt,...... from table_test 
where all_text like '%西瓜 土豆%' or 
all_text like '%土豆 青椒%' or 
all_text like '%西瓜 青椒%';

select text_title tt,...... from table_test 
where all_text like '%西瓜%' or 
all_text like '%土豆%' or 
all_text like '%青椒%';

--2.组合上述语句按匹配的长度排序显示 order by length(str)。
------解决方案--------------------
list1 = "select * from table where keyword like '%西瓜%'"
list2 = "select * from table where keyword like '%土豆%'"
list3 = "select * from table where keyword like '%青椒%'"

list1 & list2 & list3
(list1 & list2) | (list2 & list3) | (list1 & list3)
list1 | list2 | list3
------解决方案--------------------
做一个函数如f_find,输入v1_str,v2_str,v3_str(如:西瓜 土豆 青椒),
输出为v_length

在text中查找v1_str||v2_str||v3_str,如果同时查找到这三个关键词时,长度最短,则v_length应该最小;
反之v_length应该较大。

数据库中排序时使用order by f_find(v1_str,v2_str,v3_str),不加desc。


探讨
引用:
--1.分三次查询,分别按顺序显示:

select text_title tt,...... from table_test
where all_text like '%西瓜 土豆 青椒%';

select text_title tt,...... from table_test
where all_text like '%西瓜 土豆%' or
all_text like '%土豆 青椒%' or
all_text like '%西瓜 青椒%';

select text_title tt,...... from table_test
w…

------解决方案--------------------
首先我们假设你已经将包含三个单词任意一个的数据保存在临时表 #A 里边了,假设文本在 text_field 字段,接下来的排序就可以类似于

select * from #A order by (case charindex('西瓜',text_field) when 0 then 0 else 1 end)
+(case charindex('土豆',text_field) when 0 then 0 else 1 end)
+(case charindex('青椒',text_field) when 0 then 0 else 1 end)

再说前一步,对于大数据量你需要使用全文检索(SQL Server系统有全文检索系统)来搜索包含着三个关键词任何一个关键词的记录(写到#A中)。如果不使用全文检索系统,你应该自己写一个“倒排表”生成程序。从你给出的原始数据去查找,在数据量大时就慢的不得了了。