DROP TABLE IF EXISTS `t_org`;
CREATE TABLE `t_org` (
`id` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`parent_id` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_org
-- ----------------------------
INSERT INTO `t_org` VALUES ('ddd', '3', 'rty');
INSERT INTO `t_org` VALUES ('bbb', '3', 'rty');
INSERT INTO `t_org` VALUES ('ee', '3', 'rty');
INSERT INTO `t_org` VALUES ('aa', '4', 'ee');
INSERT INTO `t_org` VALUES ('rt', '2', 'zttt');
INSERT INTO `t_org` VALUES ('qqq', '4', 'ee');
INSERT INTO `t_org` VALUES ('fghh', '4', 'ee');
INSERT INTO `t_org` VALUES ('wew', '2', 'rttt');
INSERT INTO `t_org` VALUES ('jkl', '4', 'ee');
INSERT INTO `t_org` VALUES ('rty', '2', 'zttt');
INSERT INTO `t_org` VALUES ('qwe', '3', 'rty');
INSERT INTO `t_org` VALUES ('vbn', '3', 'rty');
INSERT INTO `t_org` VALUES ('zttt', '1', 'zwew');
SET FOREIGN_KEY_CHECKS = 1;
SELECT
id,
ischild
FROM
(
SELECT
t1.id,
IF
( find_in_set( parent_id, @pids ) > 0, @pids := concat( @pids, ',', id ), 0 ) AS ischild
FROM
( SELECT id, parent_id FROM t_org t ORDER BY level,parent_id, id ) t1,
( SELECT @pids := 'aaa' ) t2
) t3
WHERE
ischild != '0'
sql如上面所示,网上找的sql不加level,这样会有bug,当id和parent_id是uuid时,order by不能根据顺序排列,这样‘aaa’有可能不会最上面,concat里面就没有这个‘aaa’,就会有问题,加上level以后,就会解决这个问题。数据在上面,可以自己试试,不加level和加level的区别