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 个线程。
帮助将不胜感激,在此先感谢。
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 个线程。
帮助将不胜感激,在此先感谢。
正如@AgRizzo 上面评论的那样,您可能需要对子查询进行分组。
此外,内连接只会导致两个表中连接条件都匹配的记录:也就是说,将排除没有回复的帖子。
如果您希望保留一个表中的记录,即使连接条件不匹配,您将需要外连接;在这种情况下,左外连接(以便连接的左操作数中的记录始终包含在结果集中)。
有关详细信息,请参阅SQL 连接的可视化解释。
所以:
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