当前位置: 移动技术网 > IT编程>数据库>Mysql > mysql 关键词相关度排序方法详细示例分析

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

小项目有时需要用到关键词搜索相关性排序,用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;$i<count($q);$i++){
for($j=0;$j<count($f);$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”;

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网