Search code examples
mysqlselectgreatest-n-per-group

order and group mysql


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


Solution

  • 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