2013-01-15 59 views
0

的情況是,我已經實現了使用像運算符的搜索查詢:訂購的MySQL結果通過比賽的數量在像條款中

.. WHERE caption LIKE 'hello%' OR text LIKE '%hello' 
     OR caption LIKE 'jame%' OR text LIKE 'jame%' 

和表類似的東西:

id | caption | text 
--------------------- 
1 | Hi  | Hi Jame 
2 | Hello | Hello firend 
3 | Jame | Hello jame 

所以我期望結果集是這樣的命令:

id | caption | text 
--------------------- 
3 | Jame | Hello jame 
1 | Hi  | Hi Jame 
2 | Hello | Hello firend 

因爲第三行有更多匹配到WHERELIKE條款。

有沒有辦法做到這一點?

+1

也許這幫助http://stackoverflow.com/questions/1588710/mysql-how-to-order-by -relevance-的InnoDB表 – Sibu

回答

1
SELECT   * 
FROM  (SELECT *, 
       CASE 
         WHEN caption LIKE 'hello%' OR text LIKE '%hello' 
         THEN 1 
         WHEN caption LIKE 'jame%' OR text LIKE 'jame%' 
         THEN 2       
         ELSE 0 
       END AS weight 
     FROM your_table 
     ) 
     q 
WHERE q.weight > 0 
ORDER BY q.weight 
0

試試這個

 WHERE caption LIKE 'hello%' OR text LIKE '%hello' 
    OR caption LIKE 'jame' OR text LIKE 'jame' 
    ORDER BY caption DESC 

或更容易像

 WHERE caption LIKE 'hello' 
    OR caption LIKE 'jame' 
    ORDER BY caption DESC