比如说部门,有上级部门,是多级的,需要根据部门ID查询出所有该部门的子部门。
如果是2级,可以通过左连接联查同一张表即可。但层级数不确定的情况下,就得用sql函数或者存储过程来实现了。
数据脚本:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for apartment
-- ----------------------------
DROP TABLE IF EXISTS `apartment`;
CREATE TABLE `apartment` (
`aid` bigint(20) NOT NULL AUTO_INCREMENT,
`apartment_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '部门名称',
`description` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '部门描述',
`parent_aid` bigint(20) NULL DEFAULT NULL COMMENT '父部门ID',
`state` int(11) NULL DEFAULT NULL COMMENT '状态 0 删除 1 正常',
`create_uid` bigint(20) NULL DEFAULT NULL COMMENT '创建人ID',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
`update_uid` bigint(20) NULL DEFAULT NULL COMMENT '修改人ID',
`update_time` datetime NULL DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`aid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 15 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '部门表' ROW_FORMAT = Compact;
-- ----------------------------
-- Records of apartment
-- ----------------------------
INSERT INTO `apartment` VALUES (0, '总部门', '总部门', NULL, 1, 0, '2018-08-22 20:32:45', NULL, NULL);
INSERT INTO `apartment` VALUES (5, '语音业务部', '管语音的部门', 0, 1, 0, '2018-08-23 15:40:10', NULL, NULL);
INSERT INTO `apartment` VALUES (6, '短信业务部', '管语音的部门', 0, 1, 0, '2018-08-23 15:41:14', 0, '2018-08-24 10:27:24');
INSERT INTO `apartment` VALUES (13, 'CAAS项目组', NULL, 5, 1, 0, '2018-08-24 10:29:59', NULL, NULL);
INSERT INTO `apartment` VALUES (14, '软件项目组', NULL, 5, 1, 0, '2018-08-24 10:30:51', NULL, NULL);
SET FOREIGN_KEY_CHECKS = 1;
CREATE DEFINER=`root`@`%` FUNCTION `selectApartmentChildIdList`(apartmentId INT) RETURNS varchar(4000) CHARSET utf8
BEGIN
DECLARE aidListStr VARCHAR(4000);
DECLARE tempAid VARCHAR(4000);
SET aidListStr = '';
SET tempAid = CAST(apartmentId AS CHAR);
WHILE tempAid IS NOT NULL
DO
SET aidListStr = CONCAT( aidListStr, ',', tempAid );
SELECT GROUP_CONCAT(aid) INTO tempAid FROM apartment WHERE state > 0 AND FIND_IN_SET(parent_aid,tempAid) > 0;
END WHILE;
RETURN SUBSTRING( aidListStr, 2 );
END
TODO