Say I have three tables:
userswith names IDsemailscontaining rows which have their email addressmessagescontaining rows which contain the dates and titles of their emails
the second and third tables can all be matched to the first using the user’s ID of course.
I want a query which will return each user once only, their email address and the date of their most recent message.
If I use this:
SELECT name,email,title,date
FROM users
JOIN emails ON users.id = emails.user_id
JOIN messages ON messages.user_id = emails.user_id
group by name
order by date desc
I don’t get the most recent message, because the ordering has happened after the joining and the grouping. I get one email each from my users, and the emails are sorted by their date.
Can this be done in one join? What am I missing?
Pastebin for a dummy database you can use: http://pastebin.com/1x273aEe — the actual database is not exactly like this, but it’s the same problem.
1 Answer