Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Priority of SQL Query with multiple OR

Tags:

sql

mysql

I have two columns: name, surname (name, lastname)

In a query, try the full name (ex.: Steve Jobs), then I divide the words into the variable (in php) and do the query:

SELECT * FROM `usuarios` WHERE 
(`nome` REGEXP '$bt1 $bt2') OR 
(`nome` REGEXP '$bt1') OR 
(`sobrenome` REGEXP '$bt1') OR
(`sobrenome` REGEXP '$bt1 $bt2')

The problem is that the display of the results are not following the order of queries, then ends up returning:

Steve John
John Jobs
Steve Jobs

How do I prioritize the query and return in the case Steve Jobs?

like image 854
Gustavo Porto Avatar asked Oct 19 '25 03:10

Gustavo Porto


1 Answers

try this:

          (SELECT '1' as sb, usuarios.* FROM usuarios WHERE nom` REGEXP '$bt1 $bt2')
UNION ALL (SELECT '2' as sb, usuarios.* FROM usuarios WHERE nome REGEXP '$bt1')
UNION ALL (SELECT '3' as sb, usuarios.* FROM usuarios WHERE sobrenome REGEXP '$bt1')
UNION ALL (SELECT '4' as sb, usuarios.* FROM usuarios WHERE sobrenome REGEXP '$bt1 $bt2')
ORDER BY sb
like image 68
KM. Avatar answered Oct 21 '25 16:10

KM.