Improve the results of a select with LIKE

3

If I make a query of the type:

SELECT nombre FROM tabla WHERE nombre LIKE '%foo%'

How could you sort / filter the result so that, for example, the results that most match " foo " are displayed first?

For example, if you had: " foo ", " foooooooooo ", and " 342457fooooooooooooooo38407632069 "

How can I make the query so that " foo " is displayed first? (Because it is the closest result to what I have passed as input)

    
asked by SalvaD5100 23.08.2017 в 00:14
source

1 answer

2

Depending on what you want to consider as results that most closely match your string, you can search for different methods to calculate that match or distance between the words. The simplest would be to check the length of the chains and order from least to greatest, so the exact values will appear first:

SELECT nombre 
FROM   tabla 
WHERE  nombre like "%foo%" 
ORDER BY (LENGTH(nombre) - LENGTH("foo"))

And from there you could complicate everything you want: checking the number of occurrences of the word in the chain, comparing the position of the first occurrence, calculating the distance of Levenshtein ...

    
answered by 23.08.2017 / 01:20
source