MySQL order by relevance
There is probably a more efficient way and given the search string could be more than 2 words this probably isn't feasible, but i'd do something like
ORDER BY CASE
WHEN strTitle LIKE '%John Smith%' THEN 1
WHEN txtContent LIKE '%John Smith%' THEN 2
WHEN strTitle LIKE '%Smith John%' THEN 3
WHEN txtContent LIKE '%Smith John%' THEN 4
ELSE 5 END
I managed to get pretty spot on with this:
SELECT *,
( (1.3 * (MATCH(strTitle) AGAINST ('+john+smith' IN BOOLEAN MODE))) + (0.6 * (MATCH(txtContent) AGAINST ('+john+smith' IN BOOLEAN MODE)))) AS relevance
FROM content
WHERE (MATCH(strTitle,txtContent) AGAINST ('+john+smith' IN BOOLEAN MODE) )
ORDER BY relevance DESC
mysql fulltext search is a good thing but it has a limit of minimum 4 characters word to be indexed. Al tough the limit can be changed but changing server variables isn't possible in all scenarios. In such a situation, I recommend the solution suggested in order by case
select
*
from
mytable a
WHERE
(a.title like 'somthing%'
OR a.title like '%somthing%'
OR a.title like 'somthing%')
ORDER BY case
WHEN a.title LIKE 'somthing%' THEN 1
WHEN a.title LIKE '%somthing%' THEN 2
WHEN a.title LIKE '%somthing' THEN 3
ELSE 4 END;