需要有关子查询/组/订单的帮助(获取每个有序主题的最新评论)

时间:2010-04-21 21:34:19

标签: mysql greatest-n-per-group

嘿伙计我有一个查询,当前查找每个用户主题的最新评论,然后按该评论的时间戳排序主题。 我想要做的是扩展此查询的使用并打印每个主题的最新评论。此查询的问题在于,当它正确地命令主题时,它会为每个主题打印看似随机的注释。我正在尝试实现一个子查询,但我不太确定如何处理它。我以为我只是不得不以某种方式使用此查询来获取评论。如果有人有任何想法我会非常感激。

以下是我认为我需要添加的内容

SELECT * FROM comments where topic_id='$topic_id' ORDER BY timestamp DESC LIMIT 1

以下是我需要修改的查询

SELECT topic.topic_title, topic.content_type, topic.subject_id, topic.creator, topic.description, topic.topic_id,comments.message,comments.user
      FROM comments
      JOIN topic ON topic.topic_id = comments.topic_id
      WHERE topic.creator = '$user' AND comments.timestamp > $week
      GROUP BY topic_id ORDER BY MAX(comments.timestamp) DESC

3 个答案:

答案 0 :(得分:2)

这是一个最大的每组问题的例子,它经常出现在Stack Overflow上。请按照标记获取更多示例。

SELECT t.topic_title, t.content_type, t.subject_id, t.creator, t.description, 
  t.topic_id, c1.message, c1.user
FROM topic t
JOIN comments c1 ON (t.topic_id = c1.topic_id)
LEFT OUTER JOIN comments c2
  ON (t.topic_id = c2.topic_id AND c1.timestamp < c2.timestamp)
WHERE t.creator = ? AND c1.timestamp > ?
  AND c2.topic_id IS NULL
ORDER BY c1.timestamp DESC;

PS:对动态值使用查询参数(?),以降低SQL注入的风险。

答案 1 :(得分:0)

不确定你的$ week var在做什么,但我希望它是日期格式化的。

这个怎么样?我怀疑它会很慢,但这是我想到的第一件事:

SELECT t.topic_title, t.content_type, t.subject_id, t.creator,
   t.description, t.topic_id, c.message, c.user
FROM topic t
INNER JOIN comments c
  ON t.topic_id = c.topic_id
  AND c.comment_id = (select max(c2.comment_id) 
                    from comments c2
                    where c2.topic_id = topic.topic_id)
WHERE t.creator = '$user' 
  AND c.timestamp > $week

答案 2 :(得分:0)

select t.topic_title, t.content_type, t.subject_id, t.creator, t.description, t.topic_id, c.message, c.user
from comments c
inner join (
    SELECT cc.topic_id, max(cc.timestamp) as MaxTimestamp
    FROM comments cc
    inner JOIN topic t ON t.topic_id = cc.topic_id
    WHERE t.creator = '$user' AND cc.timestamp > $week      
    group by cc.topic_id
) cm on c.topic_id = cm.topic_id and c.timestamp = cm.MaxTimestamp
inner JOIN topic t ON t.topic_id = c.topic_id