MySQL order by relevance

强颜欢笑 提交于 2019-11-29 18:38:30

问题


I have a search form which searches a site content table to pull back appropriate results.

I want to search the title and content fields and pull back results in order of relevance. Giving highest priority to the title.

Say we had a table (tblContent) of

intID | strTitle    | txtContent

1     | Smith John  | Lorem Ipsum
2     | Lorem Ipsum | Lorem John Smith Ipsum
3     | John Smith  | Lorem Ipsum Lorem Ipsum
4     | Lorem Ipsum | Lorem Ipsum Lorem Ipsum
5     | Lorem Ipsum | Lorem Ipsum Smith John

And you were searching for "John Smith" the results should come back in the order of 3,2,1,5

How is this possible?


回答1:


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



回答2:


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;



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/15026244/mysql-order-by-relevance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!