0

i want to select the last row inserted by each id order by time DESC

s.no     id    message           status     time
1        3     this is msg 1     unread     100001
2        2     this is msg 2     read       100002
3        4     this is msg 3     read       100003
4        3     this is msg 4     unread     100004
5        2     this is msg 5     read       100005
6        3     this is msg 6     unread     100006

i am using

select * from table group by id order by MAX(time) DESC

it is giving the right id sequence but rows are interchanged

i want it like :

s.no     id    message           status     time
6        3     this is msg 6     unread     100006
5        2     this is msg 5     read       100005
3        4     this is msg 3     read       100003

help me plz

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
user1900054
  • 77
  • 1
  • 1
  • 8

2 Answers2

5

You can pull out the max time as a separate subquery, and then join it back on to the table. This will return multiple rows for an id if it has a duplicate max time.

select 
    t.s.no,
    t.id
    t.message,
    t.status,
    t.time
from 
    table t
        inner join (
        select
            id,
            max(time) maxtime
        from
            table
        group by
            id
   ) mt
       on mt.id = t.id and t.time = mt.maxtime
order by
    t.time desc
Laurence
  • 10,896
  • 1
  • 25
  • 34
1

Try this:

select * from `table` t
join (
  SELECT id, MAX(`time`) max_t
  FROM `table`
  GROUP BY id
  ) m
on (t.id=m.id and t.`time`=m.max_t)
order by m.max_t desc
geomagas
  • 3,230
  • 1
  • 17
  • 27