[MySQL] [13] grouping queries each group to take the latest piece of data

Preface: Get all the latest user to fill in an address data

text:

Error writing:

mysql5.7, the sorting sub-query has become invalid

SELECT * FROM (SELECT * FROM address ORDER BY create_time DESC) a GROUP BY user_id

method 1:

At this time, the sub-query is not just to sort, so at this sort will take effect, but limit the number of bars

SELECT * FROM (SELECT * FROM address ORDER BY create_time DESC LIMIT 10000) a GROUP BY user_id

Method 2:

To obtain the latest time and personnel ID (grouping conditions) by MAX function, then a table related query as the original data, and

Note: This way, if there are two data user_id and create_time are equal'll find out two data, this situation can only look at a 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

Reference blog:

MySQL query in each grouping latest piece of data (user-friendly) - hack day epeirogenic - blog Park
https://www.cnblogs.com/java-spring/p/11498457.html

Guess you like

Origin www.cnblogs.com/huashengweilong/p/12005743.html