简体   繁体   中英

Find multiple words in a long word and sort the results by relevance

I am doing queries to a database that stores one, very long, word in each of the records. The are no spaces, no special characters, only ualpha. Right now I am using the LIKE keyword to look for records that contain all of the words from my input. I would like the script to show me results with the highest relevance first.

So for example, I type in "be me if". This script should first return records that contain all of those words, like this:

"XSF BE NSU ME POPKL IF "

Then it would show those that contain only two of those words and then finally those that contain only one of those words.

I tried using "ORDER BY CASE" and giving points to the best matches, like this:

 - ORDER BY CASE
 - WHEN `code` LIKE '%word1%' AND `code` LIKE '%word2%' THEN 1
 - WHEN `code` LIKE '%word1%' THEN 2
 - ELSE 3 END;

It worked but when given more than three words the server crashed because it had to browse through almost 4 million records and simply couldn't handle it.

I tried fulltext search after that but it doesn't allow me to search for partial words, only prefixes.

Is there any way to achieve what I am looking for?

I would suggest adding the values. MySQL treats booleans as integers, so you can do:

order by ((code like '%word1%') +
          (code like '%word2%') +
          (code like '%word3%')
         ) desc

EDIT:

Of course, this should be after a where clause:

where code like '%word1%' or code like '%word2%' or code like '%word3%'

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