MySQL LEFT JOIN using MAX & GROUP BY on joined table?

后端 未结 3 1157
天涯浪人
天涯浪人 2021-01-31 04:37

I\'ve got two tables (members and activities) and I\'m trying to query the members with the latest activity for each member. I\'ve got it working with two queries (one to get t

3条回答
  •  攒了一身酷
    2021-01-31 05:17

    SELECT 
        members.id ,
        members.name,
        activities.code AS activity_code,
        activities.timestamp AS activity_timestamp,
        activities.description AS activity_description
    FROM 
        members
        LEFT JOIN activities
            ON members.id = activities.member_id
        LEFT JOIN 
            (
                SELECT
                    activities.member_id
                    MAX(activities.id) AS id
                FROM activities
                GROUP BY 
                    activities.member_id
            ) AS t1
            ON activities.id = t1.id
    WHERE
        t1.id IS NOT NULL
    

提交回复
热议问题