Return maximum table value in JOIN - MYSQL

Asked

Viewed 38 times

0

I need to return the last record of a table that is on JOIN of my consultation.

But my knowledge is limited and I can’t go on:

Table Services: Tabela servicos

Table situation: Tabela situacao

Result of my query: Resultado da minha consulta

My consultation

SELECT s.id_servico,
       s.titulo,
       s.valor,
       st.situacao,
       st.id_situacao
FROM   servicos s
       JOIN (SELECT id_servico,
                    Max(id_situacao) AS id_situacao,
                    situacao
             FROM   situacao
             GROUP  BY 1) st
         ON st.id_servico = s.id_servico
WHERE  s.id_servico = 2872
  • Using order by for service id does not resolve?

  • No. Returns the same thing.. the maximum id_situation, but the value (situation) is not the corresponding

1 answer

3


Your query was almost ok. Note that to make the query work you need two criteria in Join:

  • servicos.id_servico = situacao.id_servico: first Join, who connects the tables
  • situacao.id_situacao = max(situacao.id_situacao): to take the "last" record, using the max.

This second JOIN is done in the subquery, which needs to catch the MAX(id_suituacao), but needs to be grouped by id_servico, ie, "always bring the last id_situation for each id_servico".

It can be done like this:

SELECT s.id_servico, 
       s.titulo, 
       s.valor, 
       st.situacao, 
       st.id_situacao 
  FROM servicos s 
 INNER JOIN situacao st ON st.id_servico = s.id_servico
 INNER JOIN (
     select max(id_situacao) id_situacao
       from situacao
      group by id_servico) si
       ON st.id_situacao = si.id_situacao
 WHERE s.id_servico=2872;

You can see it working here: http://sqlfiddle.com/#! 9/d61e80/18

In short, the second subquery JOIN takes the largest id_situation by id_servico, and does JOIN with the "situation" table itself, which has the alias "st"

  • Perfect! Thank you.

  • if the answer solves your question, be sure to mark the answer as accepted :)

Browser other questions tagged

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