简体   繁体   中英

How can I make a SQL query that selects all rows matching a certain string then weights them based on the number of matches

How can I create an SQL query that matches multiple strings with the LIKE operator, then ORDERS results by the number of matches it gets?

Also, is there a way to then store the number of matches, so that I can later do other calculations with that number in PHP?

I'm currently working with this code from another Stack Overflow answer

SELECT searchtopics_topicid, searchtopics_content FROM searchtopics 
    WHERE searchtopics_content
         LIKE '%string1%' OR searchtopics_content 
         LIKE '%string2%' OR searchtopics_content
         LIKE '%string3%' 
    ORDER BY 
         case when searchtopics_content LIKE '%string1%' then 1 else 0 end + 
         case when searchtopics_content LIKE '%string2%' then 1 else 0 end + 
         case when searchtopics_content LIKE '%string3%' then 1 else 0 end 
    DESC

The above code looks like it should work just fine, to store the number you'd just add the ORDER BY case logic to the select list.

SELECT searchtopics_topicid
     , searchtopics_content 
     , case when searchtopics_content LIKE '%string1%' then 1 else 0 end + 
       case when searchtopics_content LIKE '%string2%' then 1 else 0 end + 
       case when searchtopics_content LIKE '%string3%' then 1 else 0 end AS hit_ct 
FROM searchtopics 
WHERE searchtopics_content LIKE '%string1%' 
   OR searchtopics_content LIKE '%string2%' 
   OR searchtopics_content LIKE '%string3%' 
ORDER BY 
     case when searchtopics_content LIKE '%string1%' then 1 else 0 end + 
     case when searchtopics_content LIKE '%string2%' then 1 else 0 end + 
     case when searchtopics_content LIKE '%string3%' then 1 else 0 end 
DESC

In MySQL you can simplify this all a bit:

    SELECT searchtopics_topicid
         , searchtopics_content 
         , searchtopics_content LIKE '%string1%' 
           + searchtopics_content LIKE '%string2%' 
           + searchtopics_content LIKE '%string3%' AS hit_ct 
    FROM searchtopics 
    WHERE searchtopics_content LIKE '%string1%' 
        + searchtopics_content LIKE '%string2%' 
        + searchtopics_content LIKE '%string3%' > 0
    ORDER BY searchtopics_content LIKE '%string1%' 
           + searchtopics_content LIKE '%string2%' 
           + searchtopics_content LIKE '%string3%' DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM