SELECT * FROM forum_posts AS post
INNER JOIN( SELECT parent AS rparent, author AS rauthor, MAX(created_at( AS rdate FROM forum_replies) AS reply
ON post.id = reply.rparent
我想从论坛中检索所有记录,并在该主题上找到1条最新回复。 问题是限制也会影响父查询,导致只返回1个线程。
提前感谢,非常感谢帮助。
答案 0 :(得分:1)
作为@AgRizzo commented above,您可能需要分组子查询。
此外,内部连接只会产生两个表中匹配连接条件的记录:即,将排除没有回复的帖子。
如果您希望保留一个表中的记录,即使连接条件不匹配,您也需要外部连接;在这种情况下,左外连接(以便连接的左操作数中的记录始终包含在结果集中)。
有关详细信息,请参阅A Visual Explanation of SQL Joins。
因此:
SELECT * FROM forum_posts AS post LEFT JOIN (
SELECT parent AS rparent
, author AS rauthor
, MAX(created_at) AS rdate
FROM forum_replies
GROUP BY parent
) AS reply ON post.id = reply.rparent
或者,在加入后执行分组:
SELECT post.*
, reply.parent AS rparent
, reply.author AS rauthor
, MAX(reply.created_at) AS rdate
FROM forum_posts AS post
LEFT JOIN forum_replies AS reply ON reply.parent = post.id
GROUP BY post.id