2014-01-11 118 views
0

如何實現名稱匹配。像「John S Smith」這樣的東西必須與mysql數據庫中的「Smith John S」匹配。即單詞可以是無序的。MySql:在類似子句中匹配的無序單詞

是否可以在單個SQL查詢中執行此操作?由於它的名稱不會超過3個字。

我的代碼在邏輯上不正確。任何幫助將不勝感激。

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

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

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

生成的SQL,我看起來像這樣。

$sql="SELECT * FROM sent WHERE 1=1 AND customer_name LIKE '%John%' AND customer_name LIKE '%S%' AND customer_name LIKE '%Smith%'" ; 
+0

我認爲你不需要爆炸名稱,你可以簡單地做它像select * from發送的地方customer_name LIKE「%」。$ name。「%」; –

+0

@abdulraziq「約翰史密斯」必須匹配「史密斯約翰S」 – coding

+0

你試過上面的查詢我給你看? –

回答

2

下面的代碼將首先發現的話&所有可能的組合,然後與數據庫 匹配它,因爲你的代碼在最大隻有3個字,所以它不是一個壞的選擇

<?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)."')" ; 




    ?> 
+1

我花了時間去做,所以請問你是否需要任何幫助,這樣我的努力不會浪費 – sanjeev

+0

不錯的努力@sanjeev –

+0

@sanjeev感謝您的努力:-)。我將在此擴展我的代碼。 – coding

相關問題