Consult MySQL with OR and AND clauses?

4

I want to list the products that are in two lines and also filter by the description, the table has the following structure:

CREATE TABLE productos (
    IMA_ARTICULO DOUBLE
    ,IMA_DESCRIPCION VARCHAR(100)
    ,IMA_LINEA DOUBLE
    ,IMA_IMPUESTO DOUBLE
    ,IMA_COSTO_PROMEDIO DOUBLE
    ,IMA_PRECIO1 DOUBLE
    ,IMA_PRECIO2 DOUBLE
    ,IMA_PRECIO3 DOUBLE
    ,IMA_PRECIO4 DOUBLE
    ,IMA_PRECIO5 DOUBLE
    ,IMA_PRECIO6 DOUBLE
    ,IMA_PRECIO7 DOUBLE
    ,IMA_PRECIO8 DOUBLE
    ,IMA_PRECIO9 DOUBLE
    ,IMA_PRECIO10 DOUBLE
    ,IMA_SUBLINEA DOUBLE
    ,IMA_DESCRIPCION_EXTENDIDA VARCHAR(100)
    ,IMA_DESCUENTO_MAXIMO DOUBLE
    ,POR_RENTABILIDAD_MINIMA DOUBLE
    ,EXISTENCIA DOUBLE
    ,PACK DOUBLE
    ,IMA_TIPO DOUBLE
);

And the query I'm doing it in the following way:

SELECT *
FROM productos
WHERE IMA_LINEA = '13'
    OR IMA_LINEA = '20'
    AND IMA_DESCRIPCION LIKE '%ggg%'
    
asked by Alldesign Web 11.10.2017 в 23:08
source

1 answer

5

What you need is to use parentheses to separate the expressions:

select * 
from productos 
where (IMA_LINEA = '13' or IMA_LINEA = '20') and IMA_DESCRIPCION like '%ggg%'

However, if you would like to search for products in more than two lines, you will have a sequence of ORs that will be extended a lot:

select * 
from productos 
where (IMA_LINEA = '13' or IMA_LINEA = '20' or IMA_LINEA = '30' or IMA_LINEA = '40') and IMA_DESCRIPCION like '%ggg%'

The best thing you can do is replace all those OR with a IN :

select * 
from productos 
where IMA_LINEA in ('13','20','30','40') and IMA_DESCRIPCION like '%ggg%'

This way you are looking for all the products that are of the line within the group ('13','20','30','40') .

    
answered by 11.10.2017 / 23:18
source