2013-03-04 60 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