我想向我的网站访问者提供对现有评论发表评论的工具,因为我们可以在stackoverflow中发表评论。
这里我创建了两个表
threads
thread_id (auto increment),
title VARCHAR(MAX),
body VARCHAR(MAX),
date datetime,
user INT
comments
comment_id INT (auto increment),
parent_id INT,
thread_id INT,
title VARCHAR(MAX),
body VARCHAR(MAX),
date datetime,
user INT
当用户在一个帖子上发表评论时,它将在评论表中保存如下
comment_id = 1211
parent_id = NULL
thread_id = 122
title = "This is the title of the comment"
body = "This is the Body of the comment"
date = 2013-04-04 13:05:44
user = "xyzuser"
假设用户对上述评论发表评论,该评论将在评论表中保存如下
comment_id = 1212
parent_id = 1211
thread_id = 122
title = "This is sample title of comment on comment"
body = "This is the Body of comment on comment";
date = 2013-04-04 15:05:44
user = "abcuser"
我使用以下查询从线程表
获取线程SELECT * FROM threads WHERE thread_id = 122
直到现在,我正在评论表中的帖子下面收到评论,如下所示
SELECT * FROM comments WHERE thread_id = 122
但是现在,我还要在每条评论下显示评论, 我试过了
SELECT * FROM comments WHERE thread_id = 122 GROUP BY parent_id
但是使用此查询会在parent_id中具有NULL值的行中发生什么,以及如何在每条注释下对注释进行排序。
任何人有任何解决方案?我应该使用哪个查询以及如何在每个注释下整理注释?
答案 0 :(得分:0)
SELECT c.* FROM comments c
LEFT JOIN
comments s
ON
s.parent_id = c.comment_id
WHERE c.thread_id = 122
GROUP BY c.comment_id
ORDER BY c.date ASC
答案 1 :(得分:0)
您使用的查询SELECT * FROM comments WHERE thread_id = 122
也会在评论下收到您的评论。您是否尝试按特定顺序获取它们?然后尝试添加order by parent_id
。或者指定您想要的顺序。
可能您甚至可以绘制一个小型记录集,向我们展示您希望查询结果的样子。因为我并不完全理解你希望它们如何。
答案 2 :(得分:0)
我不知道你是如何获得注释sql结果的数组或对象,比如数组 -
$comments = array(
array('comment_id' => '1211',
'parent_id' => NULL,
'thread_id' => '122',
'title' => 'This is the title of the comment',
'body' => 'This is the Body of the comment',
'date' => '2013-04-04 13:05:44',
'user' => 'xyzuser'),
array('comment_id' => '1212',
'parent_id' => '1211',
'thread_id' => '122',
'title' => 'This is the title of the comment',
'body' => 'This is the Body of the comment',
'date' => '2013-04-04 15:05:44',
'user' => 'abcuser'),
);
现在对数组进行排序 -
$childs = array();
foreach ($comments as &$comment) {
$childs[$comment['parent_id']][] = &$comment;
}
unset($comment);
foreach ($comments as &$comment) {
if (isset($childs[$comment['comment_id']])) {
$comment['childs'] = $childs[$comment['comment_id']];
}
}
unset($comments);
$tree = $childs[NULL];
echo "<pre>";
print_r($tree);
输出:
Array
(
[0] => Array
(
[comment_id] => 1211
[parent_id] =>
[thread_id] => 122
[title] => This is the title of the comment
[body] => This is the Body of the comment
[date] => 2013-04-04 13:05:44
[user] => xyzuser
[childs] => Array
(
[0] => Array
(
[comment_id] => 1212
[parent_id] => 1211
[thread_id] => 122
[title] => This is the title of the comment
[body] => This is the Body of the comment
[date] => 2013-04-04 15:05:44
[user] => abcuser
)
)
)
)
您也可以对对象应用相同的逻辑,以按排序顺序显示结果。