Error in Mysql query

Asked

Viewed 105 times

0

Hello! this doubt arose in mysql query;

because the status is coming different from the table?

inserir a descrição da imagem aqui

follow my consultation:

SELECT DISTINCT max(idEmbreagem) as idEmbreagem, b.prefixo as idVeiculo, max(datamontagem) as datamontagem, max(kmmontagem) as kmmontagem, max(horimetromontagem) as horimetromontagem, max(c.km) as kmatual, max(c.horimetro) as horimetroatual, a.`status`, max(tipoembreagem) as tipoembreagem, (max(c.km) - max(a.kmmontagem)) as kmrodados FROM embreagem a
              JOIN veiculos b on (a.idVeiculo=b.idVeiculo)
              JOIN hodometro c on (a.idVeiculo=c.idVeiculo)
              GROUP BY a.idVeiculo order by idVeiculo ASC

3 answers

2

Buddy, ditinct with max... something feels really bad there... =/

The fact is that the distinct and the MAX()’s are messing up the results, shuffling them... You should think about building this query.

1

Because you are bringing several max in the query, it ta shuffling the results with max of each select following the conditional.

0

If you want to get the latest data from the tables embreagem and hodometro, do so:

SELECT b.idembreagem, a.prefixo idveiculo, a.datamontagem,
       a.kmmontagem, a.horimetromontagem, c.km kmatual,
       c.horimetro horimetroatual, b.status, b.tipoembreagem,
       (c.km - a.kmmontagem) as kmrodados
FROM veiculos a
JOIN embreagem b ON b.idveiculo = a.idveiculo
JOIN hodometro c ON c.idveiculo = a.idveiculo
WHERE b.idembreagem IN (SELECT MAX(idembreagem) FROM embreagem GROUP BY idveiculo)
AND c.idhodometro IN (SELECT MAX(idhodometro) FROM hodometro GROUP BY idveiculo)
ORDER BY a.prefixo ASC

Browser other questions tagged

You are not signed in. Login or sign up in order to post.