1

i am beginner in query mysql

i have table rows and value like this

enter image description here

i want to select from the table : order by ID descending and group by Phone so result will be like this

enter image description here

pls any body help me..

i already put like this

select * from messages where 1 group by phone order by ID desc

but its wrong

thank you

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
Defr
  • 13
  • 2

3 Answers3

3

To get latest message per phone attribute you can use a self join

select a.*
from messages a
join (
    select phone, max(id) id
    from messages
    group by phone
) b on a.phone = b.phone and a.id = b.id

Or using a left join

select a.*
from messages a
left join messages b on a.phone = b.phone and a.id < b.id
where b.phone is null
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
2

Try the below query

select phone, text from messages group by phone order by id DESC
Sudhir Sapkal
  • 1,018
  • 7
  • 14
0

It will not work with the group by instead of this try below query

SELECT text,phone
FROM @tblPhone tmp
WHERE id = (SELECT MAX(Id) FROM @tblPhone tmp1 WHERE tmp1.PHONE = tmp.Phone)
ORDER BY Id desc
Rajat Jaiswal
  • 645
  • 4
  • 15