I have to optimize a rather long complex query with multiple queries inside. There is a subquery that is repeated many times as a 3rd gen SELECT:
(SELECT mc.cotmoneda2 FROM monedacotizaciones mc WHERE date(mc.`FechaHora`)<= date( p.Fechacreacion) AND mc.tipo=0 order by mc.`FechaHora`desc limit 1))
heres a reduced version of the complete query:
SELECT p.ID
,p.Tipo
, p.Numero
, p.Nombre
, e.Empresa
,(CASE p.NroMoneda WHEN 1 Then (SELECT sum(fi.ImportePrecio1/(SELECT mc.cotmoneda2 FROM monedacotizaciones mc where date(mc.`FechaHora`)<= date( p.Fechacreacion) and mc.tipo=0 order by mc.`FechaHora`desc limit 1))
FROM facturasitems fi inner join facturas f on (fi.idFactura= f.Recid)
where (f.estado =0 or f.estado =1 or f.estado =3 ) and f.idpedido = p.`recid`)
ELSE (SELECT sum(fi.ImportePrecio2)
FROM facturasitems fi inner join facturas f on (fi.idFactura= f.Recid)
where (f.estado =0 or f.estado =1 or f.estado =3 ) and f.idpedido = p.`recid`) end) as FacturadoUSA
,(SELECT sum(Ci.ImportePrecio1/(SELECT mc.cotmoneda2 FROM monedacotizaciones mc where date(mc.`FechaHora`)<= date( p.Fechacreacion) and mc.tipo=0 order by mc.`FechaHora`desc limit 1))
FROM Comprasitems ci inner join Compras C on (ci.idCompra= C.Recid)
WHERE (c.estado =0 OR c.estado =1 ) AND C.idpedido = p.`recid`) as CostoRealUSA
,(SELECT sum(dgv.importe/(SELECT mc.cotmoneda2 FROM monedacotizaciones mc where date(mc.`FechaHora`)<= date( p.Fechacreacion) and mc.tipo=0 order by mc.`FechaHora`desc limit 1))
FROM detalles_gastosvarios23 dgv
where dgv.idref = p.Recid) as GastosReales
FROM Pedidos p INNER JOIN `contactos` ON (p.`idref`=`contactos`.`idcontacto`)
INNER JOIN `empresas` e ON (contactos.`idempresa`= e.`idempresa`)
INNER JOIN `talonarios` ON (`talonarios`.`recid`= p.`idtalonario`)
WHERE (p.`fechacreacion` BETWEEN '<%fechainicio%>' AND '<%fechafin%>')
AND talonarios.NroSucursal =1
GROUP BY p.Numero
What I want to do is create a user variable containing the subquery, so that it will be reevaluated for each record, but only once per record. The way it is now it works, but takes over 3 minutes!. I have tried many different options many times but looks like Im not getting the syntax right. The thing is the user variable subquery contains a reference to p.
Thanks, sorry for my poor english.