MySQL首先显示最接近的匹配

时间:2017-02-28 14:24:43

标签: php mysql wordpress

我有一个功能,可以根据用户搜索在Wordpress类别中搜索匹配,但它运行正常,但是我想在结果顶部显示与搜索最匹配的匹配项。例如,如果用户搜索“附件”,我希望首先显示,然后显示其后显示的任何其他匹配。理想情况下,他们将通过重新命令进行排序,但我不确定如何实现这一目标。

目前,下面的代码按顺序显示它们,而不是按特异性查找。下面的代码得出以下结果。

代码返回的内容

Exhaust Accessories
Accessories
Centre Stand Accessories
Rear Stand Accessories
Side Stand Accessories

我正在使用的代码

$arr = explode(' ','Accessories');
    $str = '';
    $i = 1;
    $arrCount = count($arr);

    foreach($arr as $v){
        if($arrCount > 1 && $i == 1) { $str.= '('; }
        $str.= 'wpmj8c_terms.name LIKE "%'.$v.'%" ';
          if($arrCount > 1 && $arrCount == $i) { $str.= ')'; } elseif($arrCount > 1 && $arrCount != $i) { $str .= " OR " ;}
        $i++;
    }

$cat = $wpdb->get_results("SELECT *
    FROM wpmj8c_term_relationships
    LEFT JOIN wpmj8c_term_taxonomy
    ON (wpmj8c_term_relationships.term_taxonomy_id = wpmj8c_term_taxonomy.term_taxonomy_id)
    LEFT JOIN wpmj8c_terms on wpmj8c_term_taxonomy.term_taxonomy_id = wpmj8c_terms.term_id
    WHERE wpmj8c_term_taxonomy.taxonomy = 'product_cat'  AND  $str
    GROUP BY wpmj8c_term_taxonomy.term_id");

2 个答案:

答案 0 :(得分:0)

您好_

我会给你一个简单的解决方案但不太灵活。

所以我的想法是ORDER BY找到结果字符数。在这种情况下,我们可以假设字符较少的结果是最接近或完全匹配。

您的sql查询将如下所示:

"SELECT *
    FROM wpmj8c_term_relationships
    LEFT JOIN wpmj8c_term_taxonomy
    ON (wpmj8c_term_relationships.term_taxonomy_id = wpmj8c_term_taxonomy.term_taxonomy_id)
    LEFT JOIN wpmj8c_terms on wpmj8c_term_taxonomy.term_taxonomy_id = wpmj8c_terms.term_id
    WHERE wpmj8c_term_taxonomy.taxonomy = 'product_cat'  AND  $str
    GROUP BY wpmj8c_term_taxonomy.term_id
    ORDER BY LENGTH(wpmj8c_terms.name)"

此查询应输出以下结果:

Accessories
Exhaust Accessories
Rear Stand Accessories
Side Stand Accessories
Centre Stand Accessories

我想再次告诉你这只是一个想法,不是很灵活,但我希望你明白这一点。

祝你好运!

答案 1 :(得分:0)

您可以使用like子句搜索字符串,使用order by订购列

$arr = explode(' ','Accessories');
$str = '';
$str1 = '';
$i = 1;
$arrCount = count($arr);

foreach($arr as $v){
    if($arrCount > 1 && $i == 1) { $str.= '('; }
    $str.= 'wpmj8c_terms.name LIKE "%'.$v.'%" ';
    $str1.='OR wpmj8c_terms.name LIKE "%"';
      if($arrCount > 1 && $arrCount == $i) { $str.= ')'; } elseif($arrCount > 1 && $arrCount != $i) { $str .= " OR " ;}
    $i++;
}

$cat = $wpdb->get_results("SELECT *
FROM wpmj8c_term_relationships
LEFT JOIN wpmj8c_term_taxonomy
ON (wpmj8c_term_relationships.term_taxonomy_id = wpmj8c_term_taxonomy.term_taxonomy_id)
LEFT JOIN wpmj8c_terms on wpmj8c_term_taxonomy.term_taxonomy_id = wpmj8c_terms.term_id
WHERE wpmj8c_term_taxonomy.taxonomy = 'product_cat'  AND $str $str1 
GROUP BY wpmj8c_term_taxonomy.term_id order by wpmj8c_terms.name = $str");