Mysql 选择不同的值和最后一行


Mysql select distinct values and last row

非常简单。

msg_id    msisdn           message 
----------------------------------   
1000      661000           text1   
1001      661002           text2   
1002      661004           text3   
1003      661002           text4   
1004      661002           text5     
1005      661002           text6  

我需要获取从最新到最旧的不同 msisdn 值以及最后一行中的所有值。请理解,实际查询中有更多的列词,所以我需要获取不同的 msisdn - 以及该 msisdn 最后一行的所有数据。

msisdn     msg_id    message   
----------------------------- 
661002     1005      text6   
661004     1002      text3   
661000     1000      text1     

谢谢!

只是为了清楚。我从:

从表组中选择非重复 (MSISDN)、最大值 (msg_id) 按 MSISDN

但是,提取有关max(msg_id)的所有信息是问题所在...我需要查询中的整行,而不仅仅是msg_id...

希望现在一切都更清楚了。

您可以使用包含每msisdn最大msg_id的派生表,然后连接到此表以获取其余列:

select t1.*
from mytable as t1
inner join (
   select msisdn, max(msg_id) as last_id
   from mytable
   group by msisdn
) as t2 on t1.msisdn = t2.msisdn and t1.msg_id = t2.last_id
select msisdn,msg_id,max(message)
from table1
group by msg_id,msisdn
order by msg_id desc