1

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

这是我认为我需要添加的内容

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
4

3 回答 3

2

这是每组最大 n 问题的一个示例,它经常出现在 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注入的风险。

于 2010-04-21T21:43:40.767 回答
0

不确定您的 $week 变量在做什么,但我希望它是日期格式的。

这个怎么样?我怀疑它会很慢,但这是首先想到的:

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
于 2010-04-21T21:41:40.190 回答
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
于 2010-04-21T21:43:50.877 回答