简体   繁体   English

MySQL-按相关性排序结果(是否匹配)?

[英]MySQL - order results by relevance (MATCH AGAINST?)

I have a query that works for the most part, however the only snag seems to be the order in which the results are displayed. 我有一个查询,大部分情况下,但唯一的障碍似乎是结果显示的顺序。 I would like to display the order based on the relevance to the search or closest match; 我想根据与搜索或最接近匹配的相关性显示订单; as an example, a user might search for Accessories however the results are displayed as below and would ideally display with Accessories at the top instead. 例如,用户可以搜索“ Accessories但是结果显示如下,理想情况下将显示“ Accessories ”。

A user may also search for Exhaust Accessories and of course it would be ideal if that too displayed at the top of the results, rather than them being ordered by what appears to be the ID as it currently is. 用户也可以搜索Exhaust Accessories ,当然,如果它也显示在结果的顶部,那将是理想的选择,而不是按照当前看起来像ID的顺序对其进行排序。

I have tried using match and against but can't seem to get it working properly with my limited MySQL knowledge. 我曾尝试使用matchagainst ,但似乎无法得到它与我有限的知识,MySQL的正常工作。

Query result when searching for Accessories 搜索Accessories时查询结果

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

The code I'm working with 我正在使用的代码

$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");

How about doing a strict matching first and a union with the full text matching (so you would have the 'Accessories' first). 首先要进行严格匹配,然后再与全文匹配进行联合(这样,您将首先拥有“附件”)。 To eliminate duplications you could use the DISTINCT. 要消除重复,可以使用DISTINCT。

select DISTINCT(tab1.name) FROM (SELECT * FROM myTable WHERE name = 'Accessories' UNION SELECT * FROM myTable WHERE name LIKE '%Accessories') as tab1

I am sure you can improve the above to match your requirements. 我相信您可以改进上述内容以满足您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM