douqian5920 2017-02-28 14:24
浏览 61

MySQL首先显示最接近的匹配

I have a function that searches Wordpress categories for a match based on users search and it works fine, however I'd like to display the closest match to the search at the top of the results. If for example a user searches "Accessories", i'd like that to display first and then any other matches displayed after it. Ideally they will be ordered by relevenacy, but I'm not sure how to achieve that.

At the moment the code below displays them in order they were found in the query rather than by specificity. The code below yields the below results.

What is returned by the code

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

The code I'm using

$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条回答 默认 最新

  • dougou5852 2017-02-28 14:38
    关注

    Hello_

    I will give you a simple solution but not quite flexible.

    So my idea is to ORDER BY found results character count. In this case we can assume that the result with less characters is the nearest or exact match.

    Your sql query will look something like this:

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

    This query should output following result:

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

    Again I want to tell you this is just an idea, that is not very flexible but I hope you get the point.

    Good luck!

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度