I have multiple conditions in a query like this:
SELECT * FROM image WHERE name LIKE '%text%' AND group_id = 10 LIMIT 1
The WHERE statements consist of 3 conditions:
- Text match
- Match of a foreign key
What if I want to sort the result by relevance, so depending on:
- How exact the text is matched
- How much conditions are met at all (e.g. the text match and the foreign key)
This is two questions in one but I think some times these will be in handy in combination. By this I’m referring to a question arising from a former post of mine (Way to try multiple SELECTs till a result is available?).
Thanks in advance!
To know how exactly the text is matched, you need the
fuzzystrmatchPostgreSQL module. It provides functions asdifferenceandlevenshteinthat will give you an estimation of the similarity between two strings.Then, you can build your query with some conditions like:
You can adjust
weight_1andweight_2to give preference to the text distance or the number of conditions met.