Yes. You have learned the or
can really mess up execution plans. Try using union
instead:
SELECT a.id, p.precio
FROM anuncios a LEFT JOIN
precios p
ON p.idcentroanuncio = a.idcentro AND
a.tipoubicacion = 'centropropio' AND
p.tipocentroanuncio = 'centro'
UNION
SELECT a.id, p.precio
FROM anuncios a LEFT JOIN
precios p
ON p.idcentroanuncio = a.id AND
a.tipoubicacion = 'centropropio' AND
p.tipocentroanuncio = 'centro'
LIMIT 0 , 30;
Some notes and then a better query. First, you don't need distinct
when you have group by
. Second, this version doesn't need group by
or distinct
, because the union
takes care of making the values distinct.
For performance, you may be able to take a different route. Try this:
select p.idcentroanuncio, p.price
from precios p
where p.tipocentroanuncio = 'centro' and
(exists (select 1
from annuncios a
where p.idcentroanuncio = a.id and a.tipoubicacion = 'centropropio'
) or
exists (select 1
from annuncios a
where p.idcentroanuncio = a.idcentro and a.tipoubicacion = 'centropropio'
)
);
This may eliminate the need for the distinct
. And the subqueries can each take advantage of an index: annuncios(id, tipoubicacion)
and annuncios(idcentro, tipoubicacion)
.