search
HomeDatabaseMysql TutorialMySql数据库查询多级部门及其下的所有用户信息

关于多级别菜单栏或者权限系统中部门上下级的树形遍历,oracle中有connect by来实现,mysql没有这样的便捷途径,所以MySQL遍历数据表是我们经常会遇到的头痛问题,下面通过数据库函数来实现 1、建表 ① 机构表 CREATE TABLE `t_sys_org` ( `ID` varchar(64)

             关于多级别菜单栏或者权限系统中部门上下级的树形遍历,oracle中有connect by来实现,  mysql没有这样的便捷途径,所以MySQL遍历数据表是我们经常会遇到的头痛问题,下面通过数据库函数来实现

1、建表

     ①  机构表

      CREATE TABLE `t_sys_org` (
 
  `ID` varchar(64) NOT NULL COMMENT '主键ID',
  `CODE` varchar(60) DEFAULT NULL COMMENT '编码',
  `NAME` varchar(200) DEFAULT NULL COMMENT '机构名称',
 
 `FULLNAME` varchar(100) DEFAULT NULL,
 
 `SHORTNAME` varchar(60) DEFAULT NULL COMMENT '机构简称',
 
 `ORGCODE` varchar(60) DEFAULT NULL COMMENT '机构代码',
`PARENTID` varchar(64) DEFAULT NULL COMMENT '上级机构',
  `DEPTH` int(10) DEFAULT NULL COMMENT '深度',
 
 `SORT` varchar(24) DEFAULT NULL COMMENT '排序',
 
       `REMARK` varchar(200) DEFAULT NULL COMMENT '备注',
 
 `STATUS` varchar(4) DEFAULT NULL COMMENT '状态',
  `ORGTYPE` varchar(2) DEFAULT NULL COMMENT '机构类型',
`CODENUM` varchar(80) DEFAULT NULL COMMENT '单位代码证编号',
  `LEAGALPERSON` varchar(18) DEFAULT NULL COMMENT '机构法人',
  `LEAGALPERSONID` int(10) DEFAULT NULL COMMENT '负责人ID',
  `SPLITLEADER` varchar(80) DEFAULT NULL COMMENT '分管领导',
  `SPLITLEADERID` int(10) DEFAULT NULL COMMENT '分管领导ID',
  `ADMINLEVEL` varchar(16) DEFAULT NULL COMMENT '机构行政级别',
  `NATURE` varchar(16) DEFAULT NULL COMMENT '机构性质',
  `WORKNATUREB` varchar(100) DEFAULT NULL COMMENT '机构工作性质(大类)',
  `WORKNATUREM` varchar(16) DEFAULT NULL COMMENT '机构工作性质(中类)',
  `WORKNATURES` varchar(100) DEFAULT NULL COMMENT '机构工作性质(小类)',
  `ARECODE` varchar(16) DEFAULT NULL COMMENT '单位所隶属行政区划',
  `ADDRESS` varchar(800) DEFAULT NULL COMMENT '单位驻地与地址',
 
       `MAILCODE` varchar(16) DEFAULT NULL COMMENT '单位邮编',
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='机构表(T_SYS_ORG)';

    ②用户表

        CREATE TABLE `t_sys_user` (
  `ID` varchar(64) NOT NULL COMMENT '主键ID',
  `ACCOUNT` varchar(200) DEFAULT NULL COMMENT '账号',
   `USERNAME` varchar(60) DEFAULT NULL COMMENT '姓名',
   `PASSWORD` varchar(120) DEFAULT NULL COMMENT '密码',
  `IDCARD` varchar(72) DEFAULT NULL COMMENT '身份证号',
   `SEX` varchar(4) DEFAULT NULL COMMENT '性别',
  `CREATETIME` datetime DEFAULT NULL COMMENT '创建时间',
  `MODTIME` datetime DEFAULT NULL COMMENT '修改时间',
  `MODPWDTIME` datetime DEFAULT NULL COMMENT '修改密码时间',
  `REMARK` varchar(500) DEFAULT NULL COMMENT '备注',
  `STATUS` int(10) DEFAULT NULL COMMENT '状态',
  `ADMINLEVLE` varchar(16) DEFAULT NULL COMMENT '行政级别',
   `ALARMBELL` varchar(16) DEFAULT NULL COMMENT '警衔',
   `ARCHIVEDEPTID` decimal(10,0) DEFAULT NULL COMMENT '档案部门ID',
  `AUTHORIZED` varchar(16) DEFAULT NULL COMMENT '编制',
  `BIRTHDAY` datetime DEFAULT NULL COMMENT '出生日期',
  `BIRTHPLACE` varchar(128) DEFAULT NULL COMMENT '籍贯',
 `CREATEBY` decimal(10,0) DEFAULT NULL COMMENT '创建人',
 `EDUCATIONALBG` varchar(16) DEFAULT NULL COMMENT '最高学历',
  `MODIFYBY` decimal(10,0) DEFAULT NULL COMMENT '修改人',
  `NATION` varchar(16) DEFAULT NULL COMMENT '民族',
   `POLICENUMBER` varchar(64) DEFAULT NULL COMMENT '警号',
   `POLITICAL` varchar(16) DEFAULT NULL COMMENT '政治面貌',
  `POSITION` varchar(16) DEFAULT NULL COMMENT '职务',
  `POSITIONLEVLE` varchar(16) DEFAULT NULL COMMENT '职级',
  `SORTNO` varchar(200) DEFAULT NULL COMMENT '排序级别',
  `WORKDEPTID` varchar(64) DEFAULT NULL COMMENT '工作部门ID',
  `ORGID` varchar(64) DEFAULT NULL COMMENT '所属机构',
 `USERSTATUS` decimal(10,0) DEFAULT NULL COMMENT '用户状态',
   `COCALLSTATUS` decimal(10,0) DEFAULT NULL COMMENT '即时通同步状态',
 `COMPOSITIONDEPTID` decimal(10,0) DEFAULT NULL COMMENT '编制部门',
   `RECORDSMAGORG` varchar(100) DEFAULT NULL COMMENT '档案管理单位',
   `NICKNAME` varchar(64) DEFAULT NULL COMMENT '昵称',
  `WORKNUMBER` varchar(100) DEFAULT NULL COMMENT '工作证号',
  `USERKEY` text COMMENT '用户键值',
   `PARTJOBNO` varchar(4) DEFAULT NULL,
  `IMG_PATH` varchar(200) DEFAULT NULL COMMENT '照片路径',
  PRIMARY KEY (`ID`),
   UNIQUE KEY `ACCOUNT_UNIQUE` (`ACCOUNT`) USING BTREE,
   KEY `IND_SUSR_ORGID` (`ORGID`) USING BTREE,
  KEY `IND_SUSR_STAT` (`STATUS`) USING BTREE,
   KEY `IND_SUSR_STNO` (`SORTNO`) USING BTREE,
  KEY `IND_SUSR_USTAT` (`USERSTATUS`) USING BTREE,
  KEY `IND_SUSR_WDPID` (`WORKDEPTID`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';


3、使用FUNCTION根据指定的ID流水号获取多级部门编号(包括当前ID)
BEGIN
DECLARE sTemp VARCHAR(4000);
DECLARE sTempChd VARCHAR(4000);

SET sTemp = '$';
SET sTempChd = cast(orgId  as char);


WHILE sTempChd is not NULL DO
SET sTemp = CONCAT(sTemp,',',sTempChd);
SELECT group_concat(id) INTO sTempChd FROM t_sys_org where FIND_IN_SET(parentId,sTempChd)>0;
END WHILE;
return sTemp;
END
 
4、根据部门ID获取该部门下的所有子部门
select id from t_sys_org where  FIND_IN_SET ( id,  queryAllChildByOrg('448457')) order by code;
5、根据获取的子部门获取其所有的用户信息
select username, WORKDEPTID from t_sys_user where WORKDEPTID in select id from t_sys_org where  FIND_IN_SET ( id,  queryAllChildByOrg('448457')) order by code)

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment