使用MySQL提取最近在主题中发布的摘要

时间:2011-05-31 03:20:04

标签: mysql sql join subquery

我有一个非常基本的论坛系统。三个主要表格,Topic,Comment和User都有你想象的所有常用字段,比如自动增加主键和外键,所以我认为我不需要详细说明这一点< / p>

我要做的是获取最近发布的主题列表。列表视图应显示主题标题,初始评论/帖子的正文以及作者姓名,但列表应与最近发布的主题一起订购。

除了最基本的查询之外,我不擅长MySQL。我显然可以将其分解为多个查询,但我希望在一个查询中获得性能。

这是我首先提出的,但它会根据第一篇文章的时间对主题进行排序。

SELECT topic.id as topic_id, topic.title as topic_title, topic.datePosted as datePosted, topic.views as views, topic.numComments as numComments,
    comment.ID as commentID, comment.body as body,
user.ID as userID, user.firstName, user.lastName, user.title as user_title, user.city, user.state, user.thumbnail

FROM comment INNER JOIN topic ON comment.topicID = topic.id
INNER JOIN user ON comment.userID = user.id
WHERE comment.id
        IN (
        SELECT min( comment.id )
        FROM COMMENT INNER JOIN topic ON comment.topicID = topic.id
        GROUP BY topic.id
        )

ORDER BY commentID desc';

1 个答案:

答案 0 :(得分:0)

好的,这是我对你所要求的想法的第一次打击,每个主题中最近发布的评论列表。如果这不是您想要的,请告诉我:

SELECT
  t.title,
  t.views,
  t.numComments,
  c.id,
  c.datePosted,
  c.body,
  u.firstName,
  u.lastName
FROM
  topic AS t
    INNER JOIN
      ( SELECT
          c_inner.topicId,
          MAX(c_inner.datePosted) AS latestPosted
        FROM
          comment AS c_inner
        GROUP BY
          c_inner.topicId ) AS cmax
      ON t.id = cmax.topicId
    INNER JOIN comment AS c
      ON c.topicId = cmax.topicId AND c.datePosted = cmax.latestPosted
    INNER JOIN user AS u
      ON c.userId = u.id
ORDER BY c.datePosted DESC;

如果我误解了你要找的东西,你能发布一个你想要的结果的例子吗?