CREATE TABLE `zhkt_course_chapter` (`id` bigint NOT NULL COMMENT '唯一id',`course_id` bigint NOT NULL COMMENT '所属课程id',`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '名称',`parent_id` bigint NOT NULL DEFAULT '0' COMMENT '父级id,根级父级为0,默认0',`status` int DEFAULT '0' COMMENT '状态:0正常,1禁用,默认0',`sort` int DEFAULT NULL COMMENT '排序字段',`deleted` tinyint DEFAULT '0' COMMENT '逻辑删除:0未删除,1删除,默认0',`version` int DEFAULT NULL COMMENT '版本',`create_by` bigint DEFAULT NULL COMMENT '创建者id',`create_time` datetime DEFAULT NULL COMMENT '创建时间',`update_by` bigint DEFAULT NULL COMMENT '更新者',`update_time` datetime DEFAULT NULL COMMENT '更新时间',PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC COMMENT='智慧课堂-课程章节表';
- 查询子集sql,包含自己:
WITH RECURSIVE chapter_tree AS (SELECT id, parent_id, nameFROM zhkt_course_chapterWHERE id = 1833077834931814401 -- 这里替换为具体的ID值UNION ALLSELECT c.id, c.parent_id, c.nameFROM zhkt_course_chapter cJOIN chapter_tree ct ON c.parent_id = ct.idWHERE c.deleted = 0 -- 假设只查询未被逻辑删除的记录
)
SELECT * FROM chapter_tree;
- 查询子集sql,不包含自己:
WITH RECURSIVE chapter_tree AS (-- 种子部分:从给定ID开始SELECT id, parent_id, nameFROM zhkt_course_chapterWHERE id = 1833078203409809409 -- 这里替换为具体的ID值UNION ALL-- 递归部分:查找子节点SELECT c.id, c.parent_id, c.nameFROM zhkt_course_chapter cJOIN chapter_tree ct ON c.parent_id = ct.idWHERE c.deleted = 0 -- 假设只查询未被逻辑删除的记录
)
-- 最终查询:选择所有子节点,但排除初始ID
SELECT * FROM chapter_tree
WHERE id != 1833078203409809409; -- 排除初始ID