新建一个部门表
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的值为0
需求是根据父节点编号查询子节点名称及其孙节点个数:要求一条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