0

The scenario is that i have implemented a search query using like operator:

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

and the table is something similar to:

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

so i expect that result set to be order like this:

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

because 3rd row has more matches to WHERE and LIKEclauses.

Is there a way to do that ?

Sibu
  • 4,609
  • 2
  • 26
  • 38
Omid
  • 4,575
  • 9
  • 43
  • 74
  • 1
    maybe this help http://stackoverflow.com/questions/1588710/mysql-how-to-order-by-relevance-innodb-table – Sibu Jan 15 '13 at 09:18

2 Answers2

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
cetver
  • 11,279
  • 5
  • 36
  • 56
0

try this

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

or easier like that

     WHERE caption LIKE 'hello' 
  OR caption LIKE 'jame'
  ORDER BY caption DESC 
echo_Me
  • 37,078
  • 5
  • 58
  • 78