2010-04-21 38 views
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 

回答

2

这是最大的正每个组的问题,这往往对堆栈溢出来了的例子。按照标签查看更多示例。

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注入的风险。

+0

作品像一个魅力比尔,谢谢。你甚至没有一个子查询,我明白可以有性能问题!至于(?)的建议,我知道这些在准备好的陈述中使用。我打算用mysqli准备好的语句替换我所有的mysql语句,你有什么好的参考建议吗? – Scarface 2010-04-21 22:25:57

+1

我更喜欢使用PDO,参数的用法比mysqli简单得多。这并不难,文档中有很好的例子。 http://php.net/manual/en/pdo.prepare.php – 2010-04-21 22:30:55

+0

再次感谢比尔。 – Scarface 2010-04-21 22:41:20

0

不知道你的$每周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 
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