MySQL查询命令GROUP BY中的结果

时间:2011-05-08 18:47:09

标签: 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

5 个答案:

答案 0 :(得分:1)

您可以同时使用group by和order by。 orderby将适用于每个组。

所以      GROUP BY topics.topic_id      ORDER BY post.timestamp

(我有点担心我的参数顺序错了,但我们很好:http://dev.mysql.com/doc/refman/5.5/en/select.html

答案 1 :(得分:1)

SQL的工作方式是在WHERE子句之后创建临时结果集。然后将临时结果集中的项目分组。

这意味着您必须确保临时结果集中的所有项目(分组为单个最终结果)共享您想要拥有的字段的相同值(即它们都是“最后的回复”显示在分组数据中“)。

我将使用子查询来选择要显示的最后一个回复,并将其提供给合适的WHERE子句,而不是GROUP BY。

答案 2 :(得分:1)

您可以执行类似

的操作
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添加别名

答案 3 :(得分:0)

我认为您需要做的是按date_added排序结果并将结果限制为1,以便返回最新的主题。我希望这能指出你正确的方向

答案 4 :(得分:0)

Take it in two easy steps.


You want to find the most recent post in each category, and
then some info related to the post.

So first get the posts of interest:

    SELECT 
        MAX(topic_id) AS topic_id,
        post_id 
    FROM posts
    WHERE fcat_id = '2'
    GROUP BY topic_id

and then get "stuff" by adding on your joins:


SELECT
    tst.topic_id,
    tst.post_id,
    stuff
FROM
(
    SELECT 
        MAX(topic_id) AS topic_id,
        post_id 
    FROM posts
    WHERE fcat_id = '2'
    GROUP BY topic_id
) AS tst
LEFT JOIN users ...
LEFT JOIN topics ...