[英]Mysql select distinct values and last row
Very simple.很简单。
msg_id msisdn message
----------------------------------
1000 661000 text1
1001 661002 text2
1002 661004 text3
1003 661002 text4
1004 661002 text5
1005 661002 text6
I need to get distinct msisdn values ordered from newest to oldest and all values in that last row.我需要获取从最新到最旧的不同 msisdn 值以及最后一行中的所有值。 Please understand that there are more coluns in the real query so I need to get the distinct msisdn's - but also ALL DATA from last row with that msisdn.请理解,实际查询中有更多列,因此我需要获取不同的 msisdn - 以及该 msisdn 的最后一行的所有数据。
msisdn msg_id message
-----------------------------
661002 1005 text6
661004 1002 text3
661000 1000 text1
Thanks!谢谢!
Just to be clear.只是要清楚。 I started with:我开始于:
select distinct(msisdn), max(msg_id) from table group by msisdn按 msisdn 从表组中选择 distinct(msisdn), max(msg_id)
However pulling all info about max(msg_id) is the problem... I need that whole row in the query, not just msg_id...但是,提取有关 max(msg_id) 的所有信息是问题...我需要查询中的整行,而不仅仅是 msg_id...
Hope it's all clearer now.希望现在一切都清楚了。
You can use a derived table containing the max msg_id
per msisdn
, then join to this table to get the rest of the columns:您可以使用包含每个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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.