-1

以下查询从数据库中选择子论坛以及每个子论坛中的最后一篇文章。

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

唯一的问题,查询没有选择最后一个帖子,有什么想法吗?

论坛1

帖子2

4

1 回答 1

2

我建议使用子查询max(id)为每个帖子选择。

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
于 2013-03-04T18:03:48.167 回答