2015-06-14 49 views
0

我已经尝试了很多类似的Stack可用的问题,但是我发现所有这些问题都不断得到错误用户的user_name,我真的被卡住了花了整整一天的时间试图弄清楚这一点。MySQL:在论坛主题列表中选择最近的海报

我有一个论坛,论坛内是一个线程列表,然后在线程内人们可以发帖,当用户查看论坛,并看到线程列表时,我希望他们最近的帖子和用户名显示

这是我当前的SQL查询:

SELECT t.thread_id, t.featured, t.title, t.post_count, t.view_count, t.closed, p.post_id AS latest_reply, if(u2.user_name IS NOT NULL, u2.user_name, u.user_name) AS latest_reply_user_name, MAX(p.timestamp) as timestamp, u.user_name 
FROM forum_thread AS t 
    LEFT JOIN forum_post AS p ON(t.thread_id = p.thread_id 
     AND p.post_id=(SELECT MAX(p.post_id) FROM forum_post WHERE thread_id=p.thread_id)) 
    LEFT JOIN forum_post as p2 ON (p2.post_id = p.post_id) 
    LEFT JOIN user as u ON(t.id = u.id) 
    LEFT JOIN user as u2 ON (p2.id = u2.id) 
WHERE t.forum_id = :forum_id AND t.sticky=:sticky AND t.removed=0 
GROUP BY t.thread_id 
ORDER BY latest_reply DESC 
LIMIT :limit_bottom, :limit_top 

的问题是u2.user_name似乎是随机选择的,因此latest_reply_user_name是随机选择的。 u2.user_name应该是最近发布的用户名。

+0

如果你可以用一些示例数据创建一个SQLfiddle,它会更容易帮助。 –

+0

顺便提一句,这是*在MySQL标签下SO上最常见的问题。 – Strawberry

+0

你不需要'p2',它和'p'一样。 – Barmar

回答

0

你的子查询应该是:

(SELECT MAX(p.post_id) FROM forum_post WHERE thread_id=t.thread_id) 

让你在每个线程得到最高的职位ID。