Mysql 视图中的子查询非常慢

Mysql subquery in a view very slow

我正在尝试使用 data_coleta(日期)和 servico_id 作为基础从 table 中获取 的最后结果 。查询正在运行,但速度很慢。我该如何优化?

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

您或许可以使用索引加快此查询。

查询是:

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;

您需要以下索引进行查询:amostra_ensaio_full(cliente_id, tipo_id, servico_id).

条件tipo_id <> 1在子查询中是不必要的,但不会造成任何伤害。

感谢 Gordon,但查询仍然很慢。也许我搜索更多找到了答案。

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