1

I've build the following query

$subforumsquery = "
        SELECT
          forums.*,
          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'
        ORDER BY `id` DESC";

I don't know why, but i get the same subforum twice even that there is only 1 sub forum.

BTW, is there any way to select only the last post insted of searching all?

Thanks!

2
  • Try to change your LEFT JOIN to INNER JOIN. Commented Mar 4, 2013 at 17:31
  • please post your table schemata so we can see what you're selecting from. You can use DESCRIBE mytable or SHOW CREATE TABLE mytable Commented Mar 4, 2013 at 17:32

1 Answer 1

3

Use group by

SELECT
  forums.*,
  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

EDIT :

Use MAX with a derieved query

SELECT
  forums.*,
  posts.title   AS lastmsgtitle,
  posts.timee   AS lastmsgtime,
  posts.useraid AS lastmsguseraid,
  posts.useradn AS lastmsguseradn,
  users.photo   AS lastmsgphoto
FROM forums
  LEFT JOIN (
        SELECT  
            * 
        FROM posts
        LEFT JOIN (
                SELECT 
                    MAX(id) AS ID 
                FROM posts 
                GROUP BY forumid
            ) AS l ON l.ID = posts.id
     GROUP BY forumid) AS 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
Sign up to request clarification or add additional context in comments.

5 Comments

worked great, is there any way to set MAX() on posts. I need only the last post.
I think i'm right, but instead of adding a GROUP BY with LEFT JOIN, the INNER JOIN would be a better way...
Where do I need to set the MAX()?
Why not a LIMIT 1 at the end?
when I do "ON (posts.forumid = forums.id)" the query searching for all posts where forumid = $forumid. I need only the last post. how do i do it?

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.