MySQL using LIKE

0

I'm trying to get the data from the empleados table that have ape1em starting from a to l , only that it does not show me any.

select nomem, (numhiem+2) as invitaciones, numhiem as obsequios
from empleados
where ape1em LIKE '[A-L]%'
ORDER BY nomem asc;
    
asked by Darckan 05.02.2018 в 19:44
source

2 answers

1

Change the like part where% is placed *:

LIKE '[A-L] *' ORDER BY nomem asc;

What it does is return the records whose contents start with a letter from A to L followed by any string. I do not know if it's what you're looking for.

Or you can also use the REGEXP regular expression

where ape1em REGEXP '^ [A-L]';

    
answered by 05.02.2018 / 20:01
source
1

It seems to me that using something like LIKE [A-L]*' works in other database managers, but not in MySQL.

The query is effectively solved using regular expressions. But there are at least two problems:

  • The MySQL documentation indicates that REGEXP is used for complex searches : A regular expression is a powerful way of specifying a pattern for a complex search.
  • REGEXP does not use indexes in the table, so performance may be affected.

I will provide another way to do it, using BETWEEN . This function will use the indexes in the table.

By definition, BETWEEN is used to find data between two known ranges, which is what you want here.

For example:

SELECT 
    nomem, 
    (numhiem+2) as invitaciones, 
    numhiem as obsequios
FROM 
    empleados
WHERE
    LEFT(ape1em, 1) BETWEEN 'A' AND 'L'
ORDER BY nomem asc;

If the table or column ape1em does not have a COLLATE that is case insensitive (ci), you can instruct the query to solve this possible problem by indicating that it is executed with a COLLATE that is case insensitive :

SELECT 
    nomem, 
    (numhiem+2) as invitaciones, 
    numhiem as obsequios
FROM 
    empleados
WHERE
    LEFT(ape1em, 1) BETWEEN 'A' AND 'L'
ORDER BY nomem asc 
COLLATE utf8_general_ci;

That way, it will bring you the records that start with letters like A, á, â, b, B... l, L . This will be necessary only in the case that the table or column does not have a COLLATE that ends in _ci . (For more details on the problem of COLLATE and case-insensitive (ci) \ case-sensitive (cs) , you can consult here ).

    
answered by 05.02.2018 в 21:56