php - MySQL 查询对 GROUP BY 中的结果进行排序

标签 php mysql sql group-by

我正在编写一个论坛系统,并且正在尝试获取主题中的最后一篇文章。问题是我正在根据主题 id 对结果进行分组,但我无法找到一种方法来让最后的回复显示在分组数据中。

这是我迄今为止的查询:

   SELECT SQL_CACHE users.user_id, 
          users.username, 
          topics.title, 
          topics.topic_id,
          topics.previews,
          topics.date_added,
          posts.post_id, 
          last.username AS last_username, 
          last.user_id AS last_user_id, 
          MAX( posts.post_id ) AS last_post_id,
          posts.date_added AS last_data
     FROM `topics`
LEFT JOIN `users` ON users.user_id = topics.user_id
LEFT JOIN `posts` ON ( posts.topic_id = topics.topic_id )
LEFT JOIN `users` AS last ON ( last.user_id = posts.user_id )
    WHERE fcat_id = '2'
 GROUP BY topics.topic_id

最佳答案

你可以做类似的事情

SELECT *, `last`.`user_id` AS last_user_id FROM
(
    SELECT users.user_id, 
          users.username, 
          topics.title, 
          topics.topic_id,
          topics.previews,
          topics.date_added,
          posts.post_id, 
          MAX( posts.post_id ) AS last_post_id,
          posts.date_added AS last_data
         FROM `topics`
    LEFT JOIN `users` ON users.user_id = topics.user_id
    LEFT JOIN `posts` ON ( posts.topic_id = topics.topic_id )
        WHERE fcat_id = '2'
     GROUP BY topics.topic_id
 ) AS `tst`
LEFT JOIN `posts` ON ( posts.post_id = tst.last_post_id )
LEFT JOIN `users` AS `last` ON ( `last`.user_id = posts.post_id )

只需正确设置您的选择,并可能为子查询之外的帖子 JOIN 起别名

关于php - MySQL 查询对 GROUP BY 中的结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5929510/

相关文章:

java - HttpClient 跟随重定向

php - 特定页面的页面浏览量和页面喜欢按日期计算 php mysql

php - 如何防止 Laravel 在测试中触发事件?

php - mustache 部分和代码重用

javascript - 使用 % 符号存储电子邮件时出现问题

php - 哪个唯一 ID 用于博客和评论?

Mysql Equal String 返回 0 行,LIKE String 返回 1 行

sql - 将一个表中的列插入到具有约束的另一个表中

SQL Schema 允许用户向各种表添加注释

sql - Oracle 子查询的趣味性