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。

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

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 循环语句期间再次调用数据库以获取对评论的最后回复?

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

4

2 回答 2

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
于 2009-06-10T17:17:19.010 回答
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;
于 2009-06-10T17:15:12.383 回答