2013-03-04 75 views
1

我已經建立了下面的查詢SQL多個聯接SELECT查詢

$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"; 

我不知道爲什麼,但我得到相同甚至subforum的兩倍,只有1分論壇。

順便說一句,有沒有什麼辦法來選擇只搜索全部搜索的最後一個帖子?

謝謝!

+0

試圖改變自己的LEFT JOIN到INNER JOIN。 – JoDev 2013-03-04 17:31:14

+0

請張貼您的表格模式,以便我們可以看到您選擇的內容。你可以使用'DESCRIBE mytable'或'SHOW CREATE TABLE mytable' – dnagirl 2013-03-04 17:32:13

回答

3

使用組由

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 

編輯:

使用MAX與derieved查詢

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 
+0

+1。 。 。這是正確的答案。 – 2013-03-04 17:33:43

+0

工作得很好,有什麼方法可以在帖子上設置MAX()。我只需要最後一篇文章。 – GuyChabra 2013-03-04 17:33:49

+0

是的,你可以使用MAX和group by bygather – 2013-03-04 17:34:32