简体   繁体   中英

Mysql order by left join date

I have two tables, users and sessions. Each user can have multiple sessions. I want to get user name and the date of his most recent session. But I need to do this in such a way as to be able to return the array sorted by date of last session. Also, some of the users may not have sessions so the left join will return nothing for date.

SELECT u.name, max(s.sdate) FROM users u
LEFT JOIN sessions s ON s.uid=u.id
ORDER BY s.sdate
LIMIT 25,25

Clearly this won't work but I'd like something simple. Something similar? Note that I also need to specify which set of rows to return because of pagination. This would be page 2. I did see similar posts but they were overly complex for my use.

I have kept this simplified to keep it easy to understand.

I believe in your case u need only to group your results by user. try

SELECT u.name, max(s.sdate) AS dt FROM users u
LEFT JOIN sessions s ON s.uid=u.id
GROUP BY u.id
ORDER BY dt
LIMIT 25,25

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