MySQL order by relevance

给你一囗甜甜゛ 提交于 2019-11-30 13:09:57

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;

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

What about something along the lines of

SELECT INT(id), strTitle, txtContent
FROM tblContent
WHERE name like '%John%'
GROUP BY strTitle
ORDER BY CASE WHEN strTitle like 'John %' THEN 0
           WHEN strTitle like 'John%' THEN 1
           WHEN strTitle like '% John%' THEN 2
           ELSE 3
      END, strTitle
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!