简体   繁体   中英

I need to join three tables, group the results by one column, and display the highest value from another column

Say I have three tables:

  • users with names IDs
  • emails containing rows which have their email address
  • messages containing 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.

SELECT  a.*, b.*, c.*
FROM    users a
        INNER JOIN emails b
            ON a.ID = b.user_ID
        INNER JOIN messages c
            ON a.ID = c.user_ID
        INNER JOIN
        (
            SELECT user_id, MAX(date) maxDate
            FROM messages
            GROUP BY user_ID
        ) d ON c.user_ID = d.user_ID AND
                c.date = d.maxDate

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