2014-03-04 17 views
0

我一直在嘗試用PHP使用Like關鍵字來編寫正確的SQL搜索查詢,以根據輸入的關鍵字生成有序結果。使用PHP編寫適當的搜索查詢MySQL

這就是我想要的達到

如果我搜索「人的思想」,結果應該出來像

顯示匹配「人的思維」的結果--- 1

然後顯示「人」的結果---第二屆

然後顯示的「思維」的結果--- 3

我用下面

select * from tablename where description like % Man thinking % 

這樣的關鍵詞中,但只產生隨機的結果,而不是由我用

+1

https://dev.mysql.com/doc/refman/4.1/en/fulltext-search.html – ladieu

+0

http://use-the-index-luke.com - 讀這本書。 Wildard在查詢前會嚴重阻礙您的查詢速度。您可能需要考慮額外轉義LIKE特殊字符:_和% – Misiur

+0

如果您希望排名您應該使用全文搜索 – 2014-03-04 19:01:22

回答

0

最基本的答案,得到你想要的,也使用哪些關鍵字串排序如下ORDER BY子句中的條件:

SELECT 
    * 
FROM 
    `tablename` 
WHERE 
    description LIKE '%man thinking%' OR 
    description LIKE '%man%' OR 
    description LIKE '%thinking%' 
ORDER BY 
    description LIKE '%man thinking%' DESC, 
    description LIKE '%man%' DESC, 
    description LIKE '%thinking' DESC 

我不知道這種類型的查詢雖然性能開銷。

+0

感謝您的幫助Merioles,但是這可能不會產生排名結果,但我會盡力 –

+0

全文索引會生成排名結果 – ladieu