部分匹配MySQL查询

时间:2017-02-28 10:25:56

标签: php mysql database

我正在尝试显示包含用户搜索过的单词(或单词)的所有结果。我有一些代码在一定程度上工作,但是当一个额外的单词添加到匹配结果的末尾时,它不返回任何结果。

如果用户搜索“Fork”,它将返回与“Fork”匹配的所有结果,如果它们键入“Fork Parts”,则不会返回任何结果,因为没有名为“Fork Parts”的类别。但是,我想返回结果,因为“Fork”这个词是匹配的。

function getCat($string) {
    global $wpdb;

    $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'  && wpmj8c_terms.name LIKE '%".$string."%'
        GROUP BY wpmj8c_term_taxonomy.term_id
    ");

    echo $cat;

    foreach ($cat as $search_result) {
        echo '<li><a href="/product-category/'.$search_result->slug.'">'.$search_result->name.'</a></li>';
    }

}

<ul>
    <?php getCat("Fork"); ?>
</ul>

2 个答案:

答案 0 :(得分:0)

试试这个,

    $arr = explode(' ','this test');
    $str = '';
    foreach($arr as $v){
        $str.= 'wpmj8c_terms.name LIKE "%'.$v.'%" OR ';
    }
    $str = rtrim($str," OR ");

    $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'  &&  $str
    GROUP BY wpmj8c_term_taxonomy.term_id");

因为mysql中的空间被认为是HTAB。 试一试这应该有用。

答案 1 :(得分:0)

()会有所作为。

$arr = explode(' ','this test test1');
    $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");