You can use the function LOCATE
of MySQL
within the ORDER BY
:
SET @termo := 'car';
SELECT *
FROM tabela
WHERE campo LIKE CONCAT('%', @termo, '%')
ORDER BY LOCATE(@termo, campo);
Explaining the query
above:
- The variable
@termo
is created and receives the text that will be searched in the table;
- The
CONCAT
will put %
at the beginning and end of the text, resulting in %car%
in the case of the example, which indicates that car
may be in any position of the campo
;
- The clause
ORDER BY
will take into account the position where the searched text is in the column campo
, returning first those that have the text car
at the beginning of the text;
The result will not be the same as in the example because the method shown above does not take into account only the beginning and the end of the column campo
. Take into account the position in the whole sentence by presenting it as follows:
╔═══╦════════════╗
║ ║ campo ║
╠═══╬════════════╣
║ 1 ║ caro ║
║ 2 ║ carro ║
║ 3 ║ colocar ║
║ 4 ║ reforcar ║
╚═══╩════════════╝
LOCATE
... Returns the position of the first Occurrence of substring replace in string str.
In free translation:
... returns the position of the first occurrence of a substring replace in a string str.
CONCAT
For quoted strings, concatenation can be performed by placing the strings next to each other.
In free translation:
For highlighted strings, concatention can be performed by placing the strings one after the other.
Because the
carro
has to come first thancaro
?– Marconi
Because I want to... Kkkkk... I’m joking... Because the idea is to get first the like which is more for the beginning of the word and the rest later
– Wallace Maxters
I made a serious typo, sorry
– Wallace Maxters
I can post a solution in MSSQL and you adapted to Mysql? :)
– Marconi
@Marconi would be cool if I could adapt the question to a global SQL context
– Wallace Maxters
Jeferson posted in Mysql and I in Sql-Server, the context became an almost totally "global". = D
– Marconi