1

次のクエリを作成しました

$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 つしかないのに、同じサブフォーラムが 2 回表示されます。

ところで、すべてを検索するのではなく、最後の投稿のみを選択する方法はありますか?

ありがとう!

4

1 に答える 1

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
于 2013-03-04T17:31:29.593 に答える