MySQL order by relevance

后端 未结 4 1443
感动是毒
感动是毒 2021-01-02 08:40

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 ord

相关标签:
4条回答
  • 2021-01-02 09:00

    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
    
    0 讨论(0)
  • 2021-01-02 09:03

    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
    
    0 讨论(0)
  • 2021-01-02 09:06

    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;
    
    0 讨论(0)
  • 2021-01-02 09:11

    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
    
    0 讨论(0)
提交回复
热议问题