我尝试用json加载注释并加载更多功能,但是问题是因为不知道如何进行正确的查询,
"SELECT comments.*,
(SELECT avatar FROM users WHERE users.record_num = comments.userid) as avatar
FROM comments
WHERE content = '$id' AND approved='1'
ORDER BY comments.rating DESC
LIMIT $from, $max_results";
如果我在不使用LIMIT的情况下调用此查询会正确显示,但是当我使用LIMIT而不是问题进行调用时,问题就是示例,如果我得到的结果是每页LIMIT为3
comment 1
--comment 2 replied to comment 1
--comment 3 replied to comment 1
但应为
comment 1
--comment 2 replied to comment 1
--comment 3 replied to comment 1
comment 2
--comment 7 replied to comment 2
--comment 8 replied to comment 2
comment 6
--comment 10 replied to comment 6
因此不应以某种方式计算父注释,但我还需要从数据库中获取父ID。
答案 0 :(得分:0)
我假设您具有以下表结构:
评论
id,
post_id,
user_id,
comment,
parent,
approved,
rating
用户
record_num (which will be same as comments.user_id)
现在,如果您运行以下查询,则它将列出所需数量的主注释(其中$max_results
)(parent is 0
),但将列出每个注释的所有答复(其中parent > 0
)主要意见。为了在前端轻松管理它,我已经将答复部分转换为JSON,因此迭代主结果集将打印主要注释(在您的情况下仅为3),但如果在其中迭代{{ 1}}列/索引,那么它将列出当前主要评论的所有回复,没有任何限制。
replies
此外,我已经更改了SELECT
c.*,
IF( (u.avatar != '' and u.avatar IS NOT NULL), u.avatar, 'no-image') as avatar,
CONCAT( '[', GROUP_CONCAT( CONCAT('{"id": "', c1.id, '", "reply": "', c1.comment, '"}') SEPARATOR ',' ), ']') AS replies
FROM comments AS c
LEFT JOIN users AS u ON c.userid = u.record_num
LEFT JOIN comments AS c1 ON c.id = c1.parent
WHERE c.id = '$id' AND c.approved='1' AND c.parent = 0
GROUP BY c.id
ORDER BY comments.rating DESC
LIMIT $from, $max_results
,而不是从内部查询中获取它,而是将其替换为avatar
,因此,如果它有任何图像,它将返回图像,否则简单字符串LEFT JOIN
。
希望这可以解决您的问题...