Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 按描述顺序选择唯一行_Mysql_Sql_Greatest N Per Group - Fatal编程技术网

Mysql 按描述顺序选择唯一行

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

我想按时间描述选择每个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

您可以将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谢谢你,误解了