1. 评论的场景 类似csdn博客评论
2. 建表sql
CREATE TABLE `comment` (`id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'id',`parent_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '父级评论id(查一级,二级的时候方便)',`user_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户id',`comment_content` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '评论内容',`comment_date` datetime(0) NULL DEFAULT NULL COMMENT '评论日期',`bus_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '业务id',`type` tinyint(0) NULL DEFAULT NULL COMMENT '业务类型(1.文章 2...)',`is_author` tinyint(0) NULL DEFAULT NULL COMMENT '是否作者(1作者,0普通用户)',`replied_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '被回复评论id',`replied_user_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '被回复用户id',PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '评论表' ROW_FORMAT = Dynamic;
3. 查询全部的评论(一级二级)
SELECTp.*,b.id c_id,u.id c_user_id,u.avatar_url c_avatar_url, u.nickname c_nickname,b.comment_content c_comment_content,b.comment_date c_comment_date,IF(ISNULL(b.id),b.id,(select count(*) from sys_like where bus_id = b.id)) c_like_num,IF(ISNULL(b.id),b.id,(select count(*) from `comment` where replied_id = b.id )) c_comment_num,IF(ISNULL(b.user_id),b.user_id,IFNULL((SELECT nickname FROM wx_user WHERE id = b.replied_user_id AND del_flag = 0 ),'用户已注销')) replied_user_nickname
FROM(SELECTp.id,u.id user_id,u.avatar_url,u.nickname,p.comment_content comment_content,p.comment_date comment_date,p.is_author,COUNT( c.id ) comment_num,IF(ISNULL(p.id),p.id,(select count(*) from sys_like where bus_id = p.id)) like_numFROM`comment` p JOIN wx_user u ON u.id = p.user_id AND u.del_flag = 0LEFT JOIN `comment` c ON p.id = c.parent_idWHEREp.bus_id = '1' AND p.parent_id IS NULL GROUP BYp.id ) pLEFT JOIN `comment` b ON p.id = b.parent_idLEFT JOIN wx_user u ON u.id = b.user_id AND u.del_flag = 0
4. 评论 | 回复
一级评论只需要知道,业务类型、业务id、评论内容
即可,
回复时只需要知道,业务类型、业务id、评论内容、回复的评论id
即可
贴一段代码,捋清楚了就会发现 SoEasy
5. 评论 时间倒叙分页查询可能存在的业务问题
客户端1 :分页查询第一页数据
客户端2:插入了一条新的评论
问题:客户端1
的第二
页数据和第一
页的数据存在重复
原因:假设第一页数据下标 1-9 。客户端2插入数据0后 导致第一页数据下标为 0-8,因此第二页出现下标9
解决:表中记录一个时间戳,前端在调接口时传递时间戳,然后查询的时候多个条件:<=时间戳即可