MySQL - how to show the latest topic per thread

前端 未结 2 712
遥遥无期
遥遥无期 2021-01-07 10:00

I am trying to create SQL for retrieveing a list of latests posts for the forum thread. I have the following code:

SELECT
 item_discuss_thread_id
 , item_dis         


        
相关标签:
2条回答
  • 2021-01-07 10:32

    Try this.

    SELECT
      *
    FROM
      (SELECT item_discuss_thread_id, item_discuss_post_title, COUNT(item_discuss_thread_id) AS nb_posts
       FROM item_discuss_posts
       ORDER BY __datecolumn__)
      AS ordered_by_date
    GROUP BY
      ordered_by_date.item_discuss_thread_id
    

    Replace __datecolumn__ with the column that stores posting time.

    0 讨论(0)
  • 2021-01-07 10:48

    Ok, I came with solution myself. I used a dependent subquery to solve. This is what I have in the result:

            SELECT
                 item_discuss_threads.item_discuss_thread_id
                 , item_discuss_threads.item_discuss_thread_datetime
                 , item_discuss_threads.item_discuss_thread_title
                 , latest_posts.item_discuss_post_title
                 , latest_posts.item_discuss_post_datetime
                 , COUNT(item_discuss_posts.item_discuss_post_id) AS nb_posts
            FROM
                 item_discuss_threads
            INNER JOIN item_discuss_posts
                 ON item_discuss_threads.item_discuss_thread_id=item_discuss_posts.item_discuss_thread_id
            INNER JOIN item_discuss_posts AS latest_posts
                 ON latest_posts.item_discuss_thread_id=item_discuss_threads.item_discuss_thread_id
            WHERE
                 (
                      SELECT
                            item_discuss_post_id
                      FROM
                            item_discuss_posts AS p
                      WHERE
                            p.item_discuss_thread_id=item_discuss_posts.item_discuss_thread_id
                      ORDER BY
                            item_discuss_post_datetime DESC
                      LIMIT
                           1
                 )=latest_posts.item_discuss_post_id
            GROUP BY
                 item_discuss_threads.item_discuss_thread_id
            ORDER BY
                latest_posts.item_discuss_post_datetime DESC
    
    0 讨论(0)
提交回复
热议问题