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


    新建一个部门表

    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

  • 相关阅读:
    Node基础篇(模块和NPM)
    Node基础篇(概要)
    配置Chrome支持本地(file协议)的AJAX请求
    关于 WP 开发中.xaml 与.xaml.cs 的关系
    Windows Phone 8.1又有什么新花样
    简单聊聊今天微软的变化
    Entity Framework入门系列(1)-扯淡开篇
    一个简单的文件服务器实现方案
    网站优化之页面级缓存方案
    Windows下Memcached安装与配置实例
  • 原文地址:https://www.cnblogs.com/liuxiutianxia/p/11171847.html
Copyright © 2020-2023  润新知