根據父節點編號查詢子節點名稱,孫節點個數

新建一個部門表前端

DROP TABLE IF EXISTS `dept`;
CREATE TABLE `dept` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '標識列',
  `name` varchar(255) NOT NULL COMMENT '名稱',
  `pid` int(11) NOT NULL COMMENT '父級編號',
  `num` int(11) NOT NULL DEFAULT '100' COMMENT '排序號',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COMMENT='部門表';

-- ----------------------------
-- Records of dept
-- ----------------------------
INSERT INTO `dept` VALUES ('1', '總部', '0', '100');
INSERT INTO `dept` VALUES ('2', '市場', '1', '100');
INSERT INTO `dept` VALUES ('3', '研發', '1', '100');
INSERT INTO `dept` VALUES ('4', '財務', '1', '100');
INSERT INTO `dept` VALUES ('5', '設計', '3', '100');
INSERT INTO `dept` VALUES ('6', '運維', '3', '100');
INSERT INTO `dept` VALUES ('7', '測試', '3', '100');
INSERT INTO `dept` VALUES ('8', '開發', '3', '100');
INSERT INTO `dept` VALUES ('9', '人事', '1', '100');
INSERT INTO `dept` VALUES ('10', '行政', '1', '100');
INSERT INTO `dept` VALUES ('11', '營銷', '2', '100');
INSERT INTO `dept` VALUES ('12', '策劃', '2', '100');
INSERT INTO `dept` VALUES ('13', '售後', '2', '100');
INSERT INTO `dept` VALUES ('14', 'Java', '8', '100');
INSERT INTO `dept` VALUES ('15', '大數據', '8', '100');
INSERT INTO `dept` VALUES ('16', '.Net', '8', '100');
INSERT INTO `dept` VALUES ('17', '美工', '5', '100');
INSERT INTO `dept` VALUES ('18', '前端', '5', '100');

頂級的pid的值爲0sql

 

需求是根據父節點編號查詢子節點名稱及其孫節點個數:要求一條sql語句完成運維

-- 根據父節點編號,查詢子節點名稱,及其孫節點個數
        SELECT
            id,
            dept1.pid,
            name,
            ifnull(children,0) children
FROM ( SELECT
            id,
            pId,
            name
from dept
where pid = 3 ) dept1
LEFT JOIN (SELECT pid,count(*) children FROM dept 
where pid in (SELECT id FROM dept where pid = 3)
GROUP BY pid) dept2
on dept1.id = dept2.pid

 

相關文章
相關標籤/搜索