SQL多重连接SELECT查询与MAX()

时间:2013-03-04 17:56:10

标签: php mysql sql database

以下查询从数据库中选择子论坛,并从每个论坛中选择最后一篇帖子。

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

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

FORUMS 1

POSTS 2

1 个答案:

答案 0 :(得分: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
相关问题