简体   繁体   中英

mySQL - Select by max date and get other fields of corresponding row

I know this question is asked a lot but I couldn't solve my problem so far so I'm asking a new question.

I have this table:

Id          user_id         game_id          date
1           1               1                2015-05-25 15:05:00
2           1               2                2015-05-25 15:08:00
3           2               1                2015-05-26 16:34:23
4           2               2                2015-05-28 16:36:12
5           1               1                2015-05-27 17:24:11
6           1               2                2015-05-27 17:26:21
7           1               3                2015-05-27 17:28:47

I need to select the row for a given user_id that has the max date. For example, for user_id = 1 the correct record should be number 7.

I've tried with this query but it selects the first game_id it finds

SELECT game_id, MAX(date) AS date FROM play_tbl WHERE user_id = 1 GROUP BY user_id

Thanks in advance.

You need to start by grabbing the max date for each user like this:

SELECT user_id, MAX(date) AS latestDate
FROM myTable
GROUP BY user_id;

Once you have those values, you can join them back to your original table on the condition that the user_id and latestDate columns match so you can get the whole row. The final query is like this:

SELECT m.*
FROM myTable m
JOIN(
   SELECT user_id, MAX(date) AS latestDate
   FROM myTable
   GROUP BY user_id) tmp ON tmp.user_id = m.user_id AND tmp.latestDate = m.date;

Here is an SQL Fiddle example.

Relational databases are best processed in data sets. So you need a set of data consisting of the max date for each user AND the user's id. Then join this sub set back to the base set to get the additional columns you may want.

SELECT A.ID, A.user_ID, A.Game_ID, A.date
FROM play_tbl a
INNER JOIN (SELECT max(date) mdate, user_ID 
            FROM play_table GROUP BY user_Id) b
 on a.user_Id = B.user_ID
and A.Date = B.mdate

this generates a subset consisting of the max_date for each user, then joins back to the entire set to filter each users max date, allowing you to get additional values.

Or you could do this but I think it's less efficient. you may be able to do it using an exists as well...

SELECT A.ID, A.user_ID, A.Game_ID, A.date
FROM play_tbl a
WHERE (A.user_Id, A.Date) in 
(SELECT User_ID, max(date) date FROM play_tbl B
  WHERE a.user_Id = B.user_ID
    and A.Date = B.date
GROUP BY user_Id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM