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循环语句中再次调用数据库,以获取对注释的最后一个回复?
提前致谢,请原谅我的无知,因为我还在学习。
答案 0 :(得分: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
答案 1 :(得分: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;