2022-03-02MySQL递归查询

样例表及测试数据

CREATE TABLE `t_dept`  (
  `id` int(11) NOT NULL,
  `pid` int(11) NULL DEFAULT NULL,
  `dept_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;

INSERT INTO `t_dept` VALUES (1, -1, '总公司');
INSERT INTO `t_dept` VALUES (2, 1, '事业部');
INSERT INTO `t_dept` VALUES (21, 2, '技术开发部');
INSERT INTO `t_dept` VALUES (211, 21, 'Java开发');

递归查询所有子部门

SELECT
    * 
FROM
    ( SELECT * FROM t_dept ORDER BY pid, id ) dept,
    ( SELECT @pv := -1 ) init 
WHERE
    find_in_set( pid, @pv ) 
    AND length(@pv := concat( @pv, ',', id ))

查询结果


image.png

你可能感兴趣的:(2022-03-02MySQL递归查询)