2012-07-02 77 views
0

我正在創建一個與購物者(姓名,地址)相匹配的銀行對賬單(描述,價值,類型等)的在線系統,並希望對我目前的行爲做一些反饋這樣的:MySQL查詢搜索通過相對匹配排序的關鍵字

$array = array("keywords", "taken", "from", 
       "bank", "statements", "using", "explode", 
       "function", "using", "a", "space"); 

$i = 0; 
$r = array(); //r = relevant 

while($i<count($array)) { 

    $keyword = $array[$i]; 

    $get = mysql_query("SELECT `id` FROM `users`, `addresses` 
         LEFT JOIN `users`.`id` = `addresses`.`user` 
         WHERE (`users`.`frame` LIKE '%$keyword%' 
         OR `users`.`lname` LIKE '%$keyword%') 
         OR ((`addresses`.`address` LIKE '%$keyword%' 
         OR `addresses`.`town` LIKE '%$keyword%') 
         OR (`addresses`.`county` LIKE '%$keyword%' 
         OR `postcode`.`town` LIKE '%$keyword%'));"); 

    if(mysql_num_rows($get)) { 
    while($fetch = mysql_fetch_array($get)) { 
     list($var) = $fetch; 
     push_array($r, $var); 
    } 
    } 

    $i++; 

} 

//count the IDs that match within the relative array to see 
//which is most relative to the search 

是否有這樣做,以及保持執行時間降到最低的一個更好的辦法?數據庫完成後將處於數千個數據庫中。

回答

1

這將是更好地建設是關係每個關鍵詞給用戶的關鍵詞表,如:

keywords (keyword, user) + UNIQUE(keyword, user) 

keyword1 12 
keyword1 14 
keyword2 3 

後您填充從你想搜索的數據的關鍵詞表,查詢變得更加最佳:

SELECT users.* 
FROM keywords 
INNER JOIN users ON users.id = keywords.user 
WHERE keyword IN ('keyword1', 'keyword2') 

當然,當您更改用戶或地址表(插入,更新,刪除)時,您需要維護此表。