2014-10-07 20 views
2

我有一個mysql查詢如下。MySQL通配符像多個詞的查詢

$query="SELECT name,activity FROM appid 
where result > 5 AND name LIKE :term ORDER BY name ASC LIMIT 0,40"; 

$result = $pdo->prepare($query); 

$result->bindvalue(':term','%'.$_GET["q"].'%',PDO::PARAM_STR); 
$result->execute(); 

我想要做的是這樣的。

我已經和入門這樣,我想找到

「新聞&天氣」

但是當我鍵入

「新聞天氣」

它當然不會找它。我怎麼能夠輸入並檢索該條目?

+1

創建一個數組的分割的空間,並有數組中的每個值'OR LIKE'。 – 2014-10-07 17:32:53

+0

簡單:使用正則表達式(請參閱下面的答案) – Barranka 2014-10-07 18:08:18

回答

2

Regular expressions可以做的伎倆:

select * 
from appid 
where name rlike 'news|weather' -- Matches 'news' or 'weather' 

又如:

select * 
from appid 
where name rlike 'news.*weather' -- Matches 'news' and 'wether' 
           -- with any characters in-between or none at all 
           -- (ordered) 

只是多了一個:

select * 
from appid 
where name rlike '^news.{1,}weather$' -- Matches any text that starts with 'news' 
             -- and has at least one character before 
             -- ending with 'weather' 

定期espressions可用於創建文本非常複雜的過濾器領域。閱讀上面的鏈接瞭解更多信息。


如果你可以添加一個全文索引你的表,Full-text search可能是更好的方式去與此有關。具體來說,一個boolean Full-Text search

select * 
from appid 
where match(name) against (+news +weather) 
+0

這看起來不錯,但如何實現這一點到我的查詢使用$ _GET從用戶搜索? – Bignadad 2014-10-07 22:43:10

0

我認爲唯一可行的辦法是通過代碼:

選項A:在用代碼「%」查詢參數替換的空間,但是這當然會使多個單詞排列

選項B:將空間參數拆分並根據需要動態構建查詢,併爲每個參數添加額外的「:termN」參數。

+0

爲了更好的選擇,我建議您閱讀[MySQL中的正則表達式](http://dev.mysql.com/doc/refman/5.5/en/regexp.html) – Barranka 2014-10-07 18:15:38

+0

噢,我忘了它有那些;在我經常使用的數據中,我並沒有真正使用它們。 – Uueerdo 2014-10-07 18:17:55

+0

當有人向我介紹時,我說的完全一樣......現在我不能離開他們;) – Barranka 2014-10-07 18:22:19