Home > Database > Mysql Tutorial > body text

mysql 关键词相关度排序方法详细示例分析_MySQL

WBOY
Release: 2016-06-01 13:25:21
Original
980 people have browsed it

bitsCN.com

小项目有时需要用到关键词搜索相关性排序,用sphinx显得杀鸡用牛刀,就用mysql的order by对付下。
方法一:

select * from articles where (title LIKE '%keywords%') or (content LIKE '%helloworld%') order by ((CASE WHEN title LIKE '%keywords%' THEN 2 ELSE 0 END) + (CASE WHEN content LIKE '%helloworld%' THEN 1 ELSE 0 END)) ASC, dateline DESC

方法二:
打个比方,如果搜索关键字“IBM”,“服务器”,
首先,对搜索关键字的处理,代码如下:

$kw = preg_replace("/(/s+)|( +)+/","", $kw);//替代空格,换行,tab,中文空格
$kw = preg_replace( "/(^/s*)|(/s*$)/ ", "",$kw);//去除首尾空格
$kw = preg_replace("/(/s+)/", "", $kw);//替换多个空格为一个空格
$q = explode('',$kw);//枚举关键字

这里还需要添加一个去掉标点符号的代码,但是这段代码会出现问题,不知道如何解决。

然后是生成SQL语句的代码

$f = array(”name”,”description”); //查询的字段name=产品名,description=产品描述
$s = array(4,2); //权重,name字段匹配积分4分,description字段匹配积2分,最后按积分排序


//创建查询条件语句
for($i=0;$ifor($j=0;$j$clause[$c] = ” (”.$f[$j].” LIKE ‘%”.$q[$i].”%') “;
$score[$c] = ” IF(LOCATE('”.$q[$i].”‘, “.$f[$j].”), “.$s[$j].”, 0) “;
$c++;
}
}
$sql = “SELECT id, name, description,
(”.implode(”+”,$score).”) AS score
FROM product
WHERE (”.implode(” OR “,$clause).”)
ORDER BY score DESC”;

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!