前提 需要 Mysql8
1.评论数据库设计
1.1 mysql导出的文件,大家可以导入尝试
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for testcomment
-- ----------------------------
DROP TABLE IF EXISTS `testcomment`;
CREATE TABLE `testcomment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`super_id` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
INDEX `a1`(`super_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of testcomment
-- ----------------------------
INSERT INTO `testcomment` VALUES (1, '你好', 0);
INSERT INTO `testcomment` VALUES (2, '你好啊', 1);
INSERT INTO `testcomment` VALUES (3, '大家好', 1);
INSERT INTO `testcomment` VALUES (4, '哈哈哈', 2);
INSERT INTO `testcomment` VALUES (5, '你说啥呢', 3);
INSERT INTO `testcomment` VALUES (6, '666', 2);
INSERT INTO `testcomment` VALUES (7, '我去', 4);
INSERT INTO `testcomment` VALUES (8, '这么长', 7);
INSERT INTO `testcomment` VALUES (9, '卧槽', 7);
SET FOREIGN_KEY_CHECKS = 1;
1.2渲染的样子应该是这样,这里用excel模拟下树状评论的样子(评论前面的数字为ID)
2.需求说明,需要对于某一评论后的所有相关评论,比如 查询 7后的所有评论(8,9),2后的所有评论(4,7,8,9),为何要这样,应该某一评论后的回复不可能一次全部加载完,在某一评论后设置加载更多来按钮按需加载
3.mysql
查询实现 :with
子句
with 的用法请查看 : 官方文档
mysql根据节点id
查询所有子节点
WITH RECURSIVE r AS (
SELECT *
FROM testcomment
WHERE id = 7
UNION DISTINCT
SELECT testcomment.* FROM r,testcomment WHERE
r.id = testcomment.super_id
)
SELECT *
FROM r;
查询结果示例:(下列各图 查询语句
只有第4行条件不同
,大家根据结果对照上面的excel截图,可以发现正确查询到了所有子节点)
下图为 :id为1时
下图为 :id为2时
下图为 :id为7时
下图为 :id为3时
原创来自CSDN
:小曦曦大神