评论表设计与实现(多级评论)

  1. 首先分析评论的类型
    在这里插入图片描述
    1. 对文章的回复(也称根回复或一级回复)
    2. 对根评论的回复 (二级回复,被回复的评论id和根评论相同)
    3. 对回复的回复(二级回复,被回复的评论id和根评论不同)
  2. 抽象出数据库结构
CREATE TABLE `article_comments` (
  `id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
  `article_id` int DEFAULT NULL COMMENT '文章ID',
  `user_id` int DEFAULT NULL COMMENT '评论者ID',
  `comment_content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '评论内容',
  `like_count` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '评论喜欢数、点赞数',
  `comment_type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '回复类型: 0 针对文章的回复  1 针对评论的回复',
  `reply_user_id` int DEFAULT NULL COMMENT '被回复的评论用户ID,comment_type为1时有效',
  `reply_comment_id` int DEFAULT NULL COMMENT '被回复的评论ID,comment_type为1时有效',
  `comment_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '评论发表时间',
  `comment_ip` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '评论发表时 IP 地址',
  `root_comment_id` int DEFAULT NULL COMMENT '根评论id,comment_type为1时有效',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
  1. 各类评论的查询sql
# 对文章的回复 (article_id=1)
SELECT * FROM `article_comments` WHERE article_id=1 and comment_type=0

# 对评论的回复 (article_id=1 , root_comment_id=1)
SELECT * FROM `article_comments` WHERE article_id=1 and comment_type=1 and root_comment_id=1

# 对根评论的回复 (article_id=1 , root_comment_id=1)
SELECT * FROM `article_comments` WHERE article_id=1 and comment_type=1 and root_comment_id=1 and root_comment_id=reply_comment_id 

# 对回复的回复 (article_id=1 , root_comment_id=1)
SELECT * FROM `article_comments` WHERE article_id=1 and comment_type=1 and root_comment_id=1 and root_comment_id != reply_comment_id 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值