[Mysql]分组取最新一条

 

我有如下这张表的数据,需要根据mobile电话号码分组,每条电话取最新的数据

方案1: SELECT * from (SELECT * from model_online_forecastscore_phone0001 ORDER BY id DESC) as cn GROUP BY cn.mobile

方案2:(最佳方案): 

SELECT m1.*
FROM model_online_forecastscore_phone m1 LEFT JOIN model_online_forecastscore_phone m2
ON (m1.mobile = m2.mobile AND m1.id < m2.id) WHERE m2.id is NULL;

可以看到通过explain 看执行效率非常高,这个通过left join的知识点可以参考

http://www.mysqltutorial.org/mysql-left-join.aspx

1.不加 m1.id < m2.id 和where子句

SELECT m1.*,m2.*
FROM model_online_forecastscore_phone0001 m1 LEFT JOIN model_online_forecastscore_phone0001 m2
ON (m1.mobile = m2.mobile)

 

2..不加where条件查看结果

SELECT m1.*,m2.*
FROM model_online_forecastscore_phone0001 m1 LEFT JOIN model_online_forecastscore_phone0001 m2
ON (m1.mobile = m2.mobile AND m1.id < m2.id)

通过左连接将mobile*mobile结果累积.

关键在于左连接会以左表作为基准,如果右表没有符合条件的会以null补充。

参考:https://stackoverflow.com/questions/1313120/retrieving-the-last-record-in-each-group-mysql

posted @ 2018-12-19 15:35  安琪拉的博客(公众号)  阅读(6509)  评论(0编辑  收藏  举报