Answer the question
In order to leave comments, you need to log in
Sql sort with complex condition?
Help form a query to the table of the form:
Tab1
|num| fio |
|1|Petrov Sergey Valerievich|
|2| Smirnov Sergey Sergeevich |
|3|Ivanov Ivan Ivanovich |
|4|Sergeeva Irina Ivanovna |
|5|Skovoroda Stanislav Serafimovich|
|6|Sesame Selena Ivanovna |
On the sample of matches of the beginning of words with the string "Se" without displaying repetitions in case of a double match, and the result is sorted by the presence of matches in the first, second and third word in order. And inside match by word sort alphabetically. Example of the result:
Sezam Selena Ivanovna Sergeeva Irina Ivanovna
Petrov Sergey Valerievich
Smirnov
Se
rgei Sergeevich
Skovoroda Stanislav Serafimovich It is not possible to reduce
the table to a normal form.
Answer the question
In order to leave comments, you need to log in
to start like %se%
split the field by spaces, find the number of the word in which the occurrence
find the position in the word
PATINDEX find the position in the string, get the next character.
finally sort by word_position, word_number, next_character
And what's so difficult? Combining three regular expression searches with the desired sorting. Only the request will be slow.
SELECT `FIO` AS `fio`, 1 AS `position`
FROM `test`
WHERE `FIO` REGEXP CONCAT('^ *', :needle)
UNION SELECT `FIO`, 2
FROM `test`
WHERE `FIO` REGEXP CONCAT('^ *[^ ]+ +', :needle)
AND NOT `FIO` REGEXP CONCAT('^ *', :needle)
UNION SELECT `FIO`, 3
FROM `test`
WHERE `FIO` REGEXP CONCAT('^ *[^ ]+ +[^ +] +', :needle)
AND NOT `FIO` REGEXP CONCAT('^ *[^ ]+ +', :needle)
AND NOT `FIO` REGEXP CONCAT('^ *', :needle)
ORDER BY `position`, TRIM(`fio`);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question