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每条评论可以有多个回复,但是回复不能回复。因此,当有人回复评论时,他们插入的行将在parent 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;这可以在一次查询中实现吗?或者最好是在php loop语句期间对数据库进行另一次调用,以获取对该注释的最后一个回复?
提前感谢,请原谅我的无知,因为我还在学习。
发布于 2009-06-10 17:17:19
您可以将表重新连接到自身上:
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-10 17:15:12
试试子选择:
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;https://stackoverflow.com/questions/976922
复制相似问题