duanbi3385 2017-03-01 09:36 采纳率: 100%
浏览 241

MySQL - 按相关性排序结果(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.

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.

I have tried using match and against but can't seem to get it working properly with my limited MySQL knowledge.

Query result when searching for 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");
  • 写回答

1条回答 默认 最新

  • dongyuji7309 2017-03-01 09:41
    关注

    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.

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了