Doubt with SELECT in MYSQL database

Asked

Viewed 150 times

0

I need an sql that, in the table below, always bring the last insert to each user. I tried with distinct but it didn’t work. So in the case below sql would bring the results of row 2 and 5. Detail that there are more columns (city, parents, address, etc...) and that need to appear in the final result.

DATA----------------------ID---NOME

2017-07-17 16:37:38  || 1   || Lucas    
2017-07-17 16:38:03  || 1   || Lucas    
2017-07-17 16:38:37  || 2   || Juliana  
2017-07-17 16:38:47  || 2   || Juliana  
2017-07-17 16:39:00  || 2   || Juliana 

After all this research, I didn’t find anything. This table will have more inserts with different users (always 1 id for each user) but I only exemplified to understand.

  • https://forum.imasters.com.br/topic/512214-selecionando-item-max/? do=findComment&comment=2030107 see if it helps

  • Welcome Lucas, for the best benefit of this site start by reading this post https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-ask-questions and then also https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-ask-questions

  • Sorry any mistake, it was my first question here !

2 answers

1

I can’t open the link presented by Motta, but must be quoting the function MAX(). Just completing the query would look like this:

SELECT max(data), id, nome, cidade, pais, endereco
FROM tabela
GROUP BY id, nome, cidade, pais, endereco
ORDER BY id

For the other fields of the table, it is necessary to add each of them both in the SELECT how much in part GROUP BY.

  • Your SELECT works, but only returns id and name and there are several other columns "city, parents, address, etc..." as would be without having to list all of them in select, ie without having to do SELECT max(date), id, name, city, parents, address, .... My question is to make the author’s question more appropriate.

  • I added other columns that he mentions in the example, but without having to specify the extra columns, it’s the way you assembled them.

1


The query below solves your problem only replace tabela by your table name

SELECT t1.*
FROM tabela t1
WHERE t1.data = (SELECT MAX(t2.data)
FROM tabela t2
WHERE t2.nome = t1.nome)

Table used for testing

Tabela de teste

Outcome of the consultation

Resultado

  • Really that solved my problem, I followed in the same idea of the link of Motta, Thank you very much !!

Browser other questions tagged

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