简体   繁体   中英

Get last entry for each user in a MySQL table

I have an SQL table user_login with two columns, userId and tstamp . Each entry contains the userId of the user who logged in, as well as the associated timestamp. If a user logged in 6 times, then there are six entries associated with the user.

It's easy to obtain a list of users who logged in after a certain date, eg

SELECT DISTINCT userId FROM user_login WHERE tstamp > '2017-10-01 00:00:00' 
GROUP BY userId HAVING COUNT(*) > 0;

How can I generate a table with two columns: userId and lastLoginDate ie the last login date?

You could use:

SELECT userId, MAX(tstamp) AS lastLoginDate
FROM user_login 
WHERE tstamp > '2017-10-01 00:00:00' 
GROUP BY userId;

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