duanpa1898 2014-01-11 14:52
浏览 102
已采纳

MySql:在like子句中匹配的无序单词

How can I achieve name matching. Something like "John S Smith" must match "Smith John S" in mysql database. i.e words can be unordered.

Is it possible to do this in a single SQL query? Since it is for names it will not exceed 3 words.

My code is not logically correct. Any help would be highly appreciated.

$words=explode(" ", $name);

$sql="SELECT * FROM sent WHERE 1=1";

foreach ($words as $word)
{
    $sql.=" AND customer_name LIKE '%$word%'";
}

The Resulting SQL that I have looks like this.

$sql="SELECT * FROM sent WHERE 1=1 AND customer_name LIKE '%John%' AND customer_name LIKE '%S%' AND customer_name LIKE '%Smith%'" ;
  • 写回答

1条回答 默认 最新

  • dqnqpqv3841 2014-01-11 16:01
    关注

    Below Code will first find all the possible combination of the words & then match it with database Since your code have only 3 words at the max , hence it is not a bad option

        <?php
        $name ='John S Smith';
        $words=explode(" ", $name);;
    
        function get_all_combination($arr, $temp_string, &$collect) {
            if ($temp_string != "") 
                $collect []= $temp_string;
    
            for ($i=0; $i<sizeof($arr);$i++) {
                $arrcopy = $arr;
                $elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
                if (sizeof($arrcopy) > 0) {
                    get_all_combination($arrcopy, $temp_string ." " . $elem[0], $collect);
                } else {
                    $collect []= $temp_string. " " . $elem[0];
                }   
            }   
        }
    
        $collect = array();
        get_all_combination($words, "", $collect);
    
           /* 
            $collect now have 
    
            [0] =>  John
            [1] =>  John S
            [2] =>  John S Smith
            [3] =>  John Smith
            [4] =>  John Smith S
            [5] =>  S
            [6] =>  S John
            [7] =>  S John Smith
            [8] =>  S Smith
            [9] =>  S Smith John
            [10] =>  Smith
            [11] =>  Smith John
            [12] =>  Smith John S
            [13] =>  Smith S
            [14] =>  Smith S John 
            */
    
        $sql="SELECT * FROM sent WHERE 1=1 AND (customer_name = '".implode("' OR customer_name = '",$collect)."')" ;
    
    
    
    
        ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题