我正在尝试获取用户登录的最后时间和位置。我有2个表,一个Users表和User_Logins表。
id INT
fname VARCHAR
lname VARCHAR
team VARCHAR
id INT
user_id VARCHAR
location VARCHAR
date_time DATETIME
SELECT u.id, u.fname, u.lname, ul.location, MAX(ul.time_accessed) AS last_login_time
FROM Users AS u
INNER JOIN User_Logins AS ul
ON u.id = ul.user_id
WHERE team = 'TEST-TEAM-1'
GROUP BY u.id
现在这可以为团队中的每个用户获取最后的登录时间,但它没有给我正确的位置。我如何获得last_login_time和登录位置?
谢谢!
答案 0 :(得分:1)
您需要使用子查询并获取每个用户ID的最大评估值,然后再次与users表连接以获取详细信息。
SELECT * FROM
Users U
JOIN
(SELECT u.id, MAX(ul.time_accessed) AS last_login_time
FROM Users AS u
INNER JOIN User_Logins AS ul
ON u.id = ul.user_id
WHERE team = 'TEST-TEAM-1'
GROUP BY u.id ) T
on U.id = T.id
JOIN User_Logins ul
on ul.user_id = T.id
and ul.time_accessed = T.last_login_time