2009-06-10 56 views
1
CREATE TABLE `comments` (
    `comment_id` int(11) NOT NULL AUTO_INCREMENT, 
    `comment_parent_id` int(11) NOT NULL DEFAULT '0', 
    `user_id` int(11) NOT NULL DEFAULT '0', 
    `comment_text` varchar(200) NOT NULL DEFAULT '', 
    `comment_created` int(20) NOT NULL DEFAULT '0', 
    `comment_updated` int(20) NOT NULL DEFAULT '0', 
    `comment_replies_count` int(11) NOT NULL DEFAULT '0', 
    PRIMARY KEY (`comment_id`) 
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 

每条评论可以有多个回复,但是回复无法回复。因此,当有人回复评论时,他们插入的行将具有他们在父ID列中回复的评论的ID。带条件帮助的MySQL SELECT

我想检索所有评论,如果评论有回复,我想检索最后的回复。

SELECT c1.* 
FROM comments c1 
WHERE comment_parent_id = '0' 
ORDER BY comment_created DESC; 

So if c1.comment_replies_count > 0 I would like to... 

SELECT c2.* 
FROM comments c2 
WHERE comment_parent_id = c1.comment_id 
ORDER BY comment_created DESC Limit 1; 

这可以在1查询中实现吗?还是最好在php循环语句中再次调用数据库来获取最后一条评论回复?

在此先感谢,请原谅我的无知,因为我仍在学习。

回答

0

尝试子选择:

SELECT * FROM comments WHERE comment_parent_id in (
SELECT c1.comment_id 
FROM comments c1 
WHERE c1.comment_parent_id = '0' 
AND c1.comment_replies_count > 0 
ORDER BY comment_created DESC) 
ORDER BY comment_created DESC Limit 1; 
2

你可以加入表背到自身:

SELECT c1.*, c2.*, MAX(c2.comment_id) 
FROM comments c1 LEFT JOIN comments c2 ON c1.comment_id = c2.comment_parent_id 
WHERE c1.comment_parent_id = '0' 
GROUP BY c1.comment_id 
ORDER BY c1.comment_created DESC 
+0

党,打我给它。 – 2009-06-10 17:18:03