SQL多重连接SELECT查询

时间:2013-03-04 17:28:52

标签: php mysql sql

我构建了以下查询

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

我不知道为什么,但即使只有一个子论坛,我也会得到两次相同的子论坛。

顺便说一句,有没有办法只选择最后一个搜索所有内容的帖子?

谢谢!

1 个答案:

答案 0 :(得分: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与派生查询一起使用

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