I’m sorry if this is duplicate question, but I could’nt find anything helpful here.
So, what I’m trying to do, is to sort the results of my mySQL statement by the position of a query string inside the title
field. I tried to do this with the INSTR function, and this kinda works (even though the first result is wrong because it has an umlaut in it – maybe you also have an explanation for that = bonus points). My statement looks like this (query string is ‘all’ in this case):
SELECT title, translation, INSTR(title, 'all') as posititon
FROM `dictionary`
WHERE title LIKE '%all%'
ORDER BY posititon
The result looks like this:
So far, so good. But I also want to have results that match the query string in the field ‘description’. So when I add OR translation LIKE '%all%'
in the WHERE clause, I get a totally different result:
SELECT title, translation, INSTR(title, 'all') as posititon
FROM `dictionary`
WHERE (title LIKE '%all%' OR translation LIKE '%all%')
ORDER BY posititon
Result:
So my goal would be to sort the result PRIMARY by the position of the query string in the field ‘title’ and SECONDARY by the position of the query string in the field ‘translation’.
Can you please help me with that?
2
Answers
I think regexp_like may help for getting the position:
output:
Note: of course you need to expand the regular expression (
[aä]
) with all possible values likeá
,à
, etc.This does not deal with the accent-sensitivity issue, addressed in Luuk’s answer.
Because both INSTR() and REGEXP_INSTR() return
0
when the needle is not found, you need to change the0
to something else to stop them coming first in the sort.Here’s one way:
-ti_pos DESC
is the same asti_pos ASC
but with the NULLs moved to the end.Outputs:
Or for something where the intent is more obvious: