php - 带有 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。
解决方案
我假设您具有以下表结构:
注释
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 个)但在其中,如果您迭代replies
column/ 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
。
希望这能解决您的问题...
推荐阅读
- list - 在 Haskell 中打印列表 new
- java - 范围报告中的 Base64 图像屏幕截图在单击报告中的屏幕截图时显示垃圾值
- amcharts - 工具提示中的本地化日期格式
- tensorflow - 无论提供任何图像,TFLite 都会得到相同的结果
- pentaho - Pentaho - 连接不稳定时重新连接选项
- gitlab - 如何重置 Gitlab CI/CD 共享运行器网络资源?
- firebase - 如何在来自 Firebase 的谷歌地图中显示标记?
- python - Django 与 python ayncio 执行后台任务
- algorithm - 查找通过查找所有唯一路径的“最短索引范围”的大小
- ios - 选中 MKMapView“显示用户位置”框时,活动指示器不起作用