小项目有时需要用到关键词搜索相关性排序,用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
复制代码 代码如下:
$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”;
新闻热点
疑难解答