首页 > 解决方案 > 带有 LIMIT 的线程评论

问题描述

我尝试使用 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。

标签: phpmysql

解决方案


我假设您具有以下表结构:

注释

id,
post_id,
user_id,
comment,
parent,
approved,
rating

用户

record_num (which will be same as comments.user_id)

现在,如果您运行以下查询,那么它将列出所需数量 ( $max_results) 的主要评论 (where parent is 0),但会列出每个主要评论的所有回复 (where parent > 0)。为了在前端轻松管理它,我已将回复部分转换为 JSON,因此迭代主要结果集将打印主要评论(在您的情况下只有 3 个)但在其中,如果您迭代repliescolumn/ index 然后它将列出对当前主要评论的所有回复,没有任何限制。

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, 而不是从内部查询中获取它,而是将其替换为 aLEFT JOIN所以如果它有任何图像,那么它将返回图像,否则返回简单的字符串no-image

希望这能解决您的问题...


推荐阅读