简体   繁体   中英

SQL multiple joins SELECT query with MAX()

The following query select the subforums from the database and the last posts in each one of them.

SELECT
    forums.*,
    MAX(posts.id),
    posts.title AS lastmsgtitle,
    posts.timee AS lastmsgtime,
    posts.useraid AS lastmsguseraid,
    posts.useradn AS lastmsguseradn,
    users.photo AS lastmsgphoto
FROM forums
    LEFT JOIN posts
        ON(posts.forumid = forums.id)
    LEFT JOIN users
        ON(posts.useraid = users.id)
WHERE forums.relatedto='$forumid'
    and posts.type='post'
GROUP BY forums.id
ORDER BY `id` DESC

The only problem, the query not select the last post, any ideas why?

FORUMS 1

POSTS 2

I would suggest using a subquery to select the max(id) for each post.

SELECT
    f.*,  -- replace the f.* with the columns that you need to return
    p1.MaxId,
    p2.title AS lastmsgtitle,
    p2.timee AS lastmsgtime,
    p2.useraid AS lastmsguseraid,
    p2.useradn AS lastmsguseradn,
    u.photo AS lastmsgphoto
FROM forums f
LEFT JOIN
(
    select MAX(id) MaxId, forumid
    from posts
    group by forumid
) p1
    ON p1.forumid = f.id
LEFT JOIN posts p2
    ON p2.forumid = f.id
    and p1.MaxId = p2.id
    and p2.type='post'
LEFT JOIN users u
    ON p2.useraid = u.id
WHERE f.relatedto='$forumid'
ORDER BY `id` DESC

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