M
M
MichailNikiforov2016-11-04 17:21:53
SQL
MichailNikiforov, 2016-11-04 17:21:53

How to select records with max SQL items?

There are 2 tables in the database - users with id and name fields
and User_log with user_id and login_time fields.
We need a query that will give a selection with the user_name, last_login fields (this is the login_time of the user's last authorization). If USER_LOGINS does not contain information about user authorizations, the value should be empty.
My variant produces one entry, just with the most recent login_time, not per user.
SELECT users.id, MAX(User_log.login_time) AS user_name, last_login FROM users, user_log WHERE users.id = user_log.user_id
Please help!
UPD did!
Here is the correct answer:
SELECT users.Name AS user_name, user_logins.Login_time AS last_login
FROM users
LEFT OUTER JOIN
user_logins
ON users.ID = user_logins.User_id
WHERE
user_logins.Login_time IN
(SELECT MAX(Login_time) FROM user_logins WHERE users.ID = user_logins.User_id) OR user_logins.Login_time IS NULL; It
helped

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wscms, 2016-11-04
@wscms

SELECT u.*, max(ul.login_time) as login_time FROM users u
LEFT OUTER JOIN user_log ul ON u.id = ul.user_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question