I'm trying get last result from a table using the data_coleta (DATE) and servico_id as base. The query is working but is very slow. How can I optimize?
select t1.* from
amostra_ensaio_full t1
where
t1.cliente_id = 6 and t1.tipo_id <> 1
and t1.data_coleta = (SELECT max(s1.data_coleta) from amostra_ensaio_full s1 where t1.cliente_id = s1.cliente_id and s1.tipo_id <> 1 and s1.tipo_id = t1.tipo_id)
and t1.servico_id = (SELECT max(s2.servico_id) from amostra_ensaio_full s2 where t1.cliente_id = s2.cliente_id and s2.tipo_id <> 1 and s2.tipo_id = t1.tipo_id)
GROUP by t1.cliente_id , t1.tipo_id
You can probably speed up this query using indexes.
The query is:
select t1.*
from amostra_ensaio_full t1
where t1.cliente_id = 6 and t1.tipo_id <> 1 and
t1.data_coleta = (SELECT max(s1.data_coleta)
from amostra_ensaio_full s1
where t1.cliente_id = s1.cliente_id and
s1.tipo_id <> 1 and
s1.tipo_id = t1.tipo_id
) and
t1.servico_id = (SELECT max(s2.servico_id)
from amostra_ensaio_full s2
where t1.cliente_id = s2.cliente_id and
s2.tipo_id <> 1 and
s2.tipo_id = t1.tipo_id
)
GROUP by t1.cliente_id , t1.tipo_id;
You want the following index for the query: amostra_ensaio_full(cliente_id, tipo_id, servico_id)
.
The condition tipo_id <> 1
is unnecessary in the subquery, but it causes no harm.
Tks Gordon but the query still slow. Maybe I found the answer searching more.
SELECT a.*
FROM amostra_ensaio_full a
INNER JOIN
(
SELECT MAX(data_coleta) maxDate , tipo_id, cliente_id
FROM amostra_ensaio_full
GROUP BY cliente_id, tipo_id
) b ON a.cliente_id = b.cliente_id and a.tipo_id = b.tipo_id and b.maxDate = a.data_coleta
GROUP by a.cliente_id ,a.tipo_id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.