0
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 

I want to retrieve all records from forum with 1 latest reply on that thread. Problem is the limit also effects the parent query resulting in only 1 thread being returned.

Help will be greatly appreciated, thanks in advance.

5
  • Post the show create table and example data on sqlfriddle and post the link here.. Commented Oct 13, 2013 at 12:29
  • 1
    I see no limit in there Commented Oct 13, 2013 at 12:29
  • Did you copy this code, or retype it? You have a typo - MAX should have a left parenthesis at the end. And should there be a GROUP BY clause for that MAX? Commented Oct 13, 2013 at 12:31
  • 1
    If the problem here is that posts with no replies are undesirably excluded from your resultset, you should change from an INNER JOIN to a LEFT JOIN. See A Visual Explanation of SQL Joins for more information. Commented Oct 13, 2013 at 12:53
  • Fantastic eggyal that worked perfectly! post it as a solution and ill mark it as solved. Commented Oct 13, 2013 at 12:56

1 Answer 1

1
  1. As @AgRizzo commented above, you probably need to group the subquery.

  2. Furthermore, an inner join will only result in a record where the join criterion is matched in both tables: that is, posts for which there are no replies will be excluded.

    If you wish to keep records from one table even where the join criterion is not matched, you will need an outer join; in this case, a left outer join (so that records from the left operand of the join are always included in the resultset).

    See A Visual Explanation of SQL Joins for more information.

Therefore:

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

Alternatively, perform the grouping after the join:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.