• 根据父节点编号查询子节点名称,孙节点个数


    新建一个部门表

    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

  • 相关阅读:
    [Jenkins] TestComplete 使用Jenkins进行持续集成测试
    selenium 使用close和quit关闭driver的不同点
    sleep和wait的区别
    Appium-测试失败后获取屏幕截图的方法
    sql优化的几种方式
    【Fine学习笔记】python 文件l操作方法整理
    【Fine学习笔记】Xcode的快捷方式
    【Fine学习笔记】Jmeter笔记
    【Fine原创】常见的HTTP错误码的具体含义整理
    【Fine原创】JMeter分布式测试中踩过的那些坑
  • 原文地址:https://www.cnblogs.com/liuxiutianxia/p/11171847.html
Copyright © 2020-2023  润新知