Mysql 按描述顺序选择唯一行
我想按时间描述选择每个id订单插入的最后一行Mysql 按描述顺序选择唯一行,mysql,sql,greatest-n-per-group,Mysql,Sql,Greatest N Per Group,我想按时间描述选择每个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 ms
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您可以将max time作为一个单独的子查询取出,然后将其重新连接到表中。如果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
您可以将max time作为一个单独的子查询取出,然后将其重新连接到表中。如果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
试试这个:
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
试试这个:
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
你所说的
行互换是什么意思?
?我以为你在上接受了答案。你的预期结果是什么?@MillerKoijam-这是问题中的问题。在短语“i want it like”之后:“它给出每个ID输入的第一行。你所说的行交换是什么意思?
?我以为你接受了关于的答案。你的预期结果是什么?@MillerKoijam-这是问题中的问题。在短语“i want it like”之后,它给出了每个用户输入的第一行id@MartinSmith谢谢你,misunderstood@MartinSmith谢谢你,误解了