有些复杂的MySQL声明

时间:2011-05-11 23:31:53

标签: mysql sql aggregate-functions

我正在创建一个论坛,并且已经卡住创建将显示给定论坛的所有主题的页面。三个相关表格&字段的结构如下:

Table: forums_topics    Table: forums_posts    Table: users
--------------------    -------------------    ------------
int id                  int id                 int id
int forum_id            int topic_id           varchar name
int creator             int poster
tinyint sticky          varchar subject
                        timestamp posted_on

我已经开始使用以下SQL:

   SELECT t.id, 
          t.sticky, 
          u.name AS creator, 
          p.subject, 
          COUNT(p.id) AS posts,
          MAX(p.posted_on) AS last_post
     FROM forums_topics AS t
     JOIN users AS u
LEFT JOIN forums_posts AS p ON p.topic_id = t.id
    WHERE t.forum_id = 1 
      AND u.id = t.creator
 GROUP BY t.id
 ORDER BY t.sticky

这似乎让我得到了我想要的东西(主题的id号码,如果它是粘性的,谁制作了主题,话题的主题,每个主题的帖子数量以及最新帖子的时间戳)。如果有错误,请告诉我。

我现在遇到的麻烦是我可以添加到这个以获得最新海报的名称。有人可以解释我如何编辑我的SQL来做到这一点?如果需要,我可以提供更多详细信息,或者重构我的表格,如果这样可以使其更简单。

1 个答案:

答案 0 :(得分:1)

这是一种简单的方法:

SELECT t.id, 
      t.sticky, 
      u.name AS creator, 
      p.subject, 
      COUNT(p.id) AS posts,
      MAX(p.posted_on) AS last_post,
      (SELECT name FROM users 
       JOIN forums_posts ON forums_posts.poster = users.id 
       WHERE forums_posts.id = MAX(p.id)) AS LastPoster
 FROM forums_topics AS t
 JOIN users AS u
LEFT JOIN forums_posts AS p ON p.topic_id = t.id
WHERE t.forum_id = 1 
  AND u.id = t.creator
GROUP BY t.id
ORDER BY t.sticky

基本上,您执行子查询以根据最大ID查找用户。如果您的ID是GUID或由于某些其他原因而无法使用,则可以基于published_on时间戳进行查找。