我正在尝试在标题,作者和文本三个字段上创建关键字搜索。我希望它们按相关性排序,所以我在任何字段中的匹配都给一分。我还有一个名为标签的表,它在每行中存储故事的特定标签。如果标签上有匹配项,我会在相关性中添加标签的使用次数。当用户输入搜索时,他可能会输入一系列关键字。我正在考虑分解字符串并使用 for 循环为每个关键字添加下面 select 语句中的代码。这似乎相当复杂,所以我想知道是否有更好的方法来做到这一点?
select text, ((case when S.sid in (select sid from tags where tahname like 'db')
then (select uses from tags T where S.sid = T.sid and tagname like 'db') +
(case when title like '%db%' then 1 else 0 end) +
(case when author like '%db%' then 1 else 0 end) +
(case when text like '%db%' then 1 else 0 end)) as relevance
from stories S
order by relevance desc
谢谢。
是的,有更好的方法来进行关键字搜索。
您正在使用的方法将强制进行表扫描,这意味着它必须读取表中的每一行。 根据表中最终的数据量,此操作的运行速度可能比使用专门的全文索引方法慢数百或数千倍。
查看我的演示文稿全文搜索抛弃,其中包含不同解决方案的比较。 包括:
- MyISAM表或MySQL 5.6中InnoDB的全文索引
- Apache Solr
- 狮身人面像搜索
- 三卦
您可以使用 mysql 的全文搜索功能
http://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html
甚至更好地使用为搜索而开发的东西
http://sphinxsearch.com/