标签:limit tin user weight inner order 博客 address use
前言:获取所有用户填写的最新一条地址数据
正文:
错误写法:
mysql5.7时,子查询的排序已经变为无效了
SELECT * FROM (SELECT * FROM address ORDER BY create_time DESC) a GROUP BY user_id
方法1:
此时子查询就不光是排序,所以此时排序会生效,但有条数限制
SELECT * FROM (SELECT * FROM address ORDER BY create_time DESC LIMIT 10000) a GROUP BY user_id
方法2:
通过MAX函数获取最新的时间和人员ID(分组条件),然后作为一张表和原来的数据进行联查
注:这种方式如果有两条数据的user_id和create_time都相等会查出来两条数据,这种情况只能distinct一下了
SELECT t.* FROM (SELECT user_id, max(create_time) as create_time FROM address GROUP BY user_id) a INNER JOIN address t ON t.user_id = a.user_id and t.create_time=a.create_time
参考博客:
MySQL分组查询每组最新的一条数据(通俗易懂) - 劈天造陆 - 博客园
https://www.cnblogs.com/java-spring/p/11498457.html
标签:limit tin user weight inner order 博客 address use
原文地址:https://www.cnblogs.com/huashengweilong/p/12005743.html