我想按时间DESC
选择每个id顺序插入的最后一行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
我正在使用
select * from table group by id order by MAX(time) DESC
它给出了正确的id
序列,但是行被互换了
我希望它像:
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
帮我plz
答案 0 :(得分:5)
您可以将最长时间作为单独的子查询拉出,然后将其重新连接到表中。如果它具有重复的最大时间,则会为id返回多行。
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
答案 1 :(得分:1)
试试这个:
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