1

Table users

  • id - Primary Key, AI
  • username - varchar (50)

Table logins

  • login_time - DateTime
  • member_id - int (11)

This SQL selects mid and max login_time and sorts DESC
SELECT member_id, max(login_time) as time FROM logins GROUP BY member_id ORDER BY time DESC

Question
How do you select and join username onto member_id for each row?

2 Answers 2

1
SELECT u.username, max(l.login_time) as time FROM logins l
LEFT JOIN users u ON (l.member_id = u.id)
GROUP BY l.member_id ORDER BY time DESC
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT l.member_id, max(l.login_time) as time, u.username FROM logins as l
join users as u on u.id = l.member_id
GROUP BY l.member_id ORDER BY l.time DESC

1 Comment

MYSQL throws an error for ORDER BY l.time. I prefer to write 'table t', rather than use the keyword 'as' which is generally used for column aliases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.