Home > Database > Mysql Tutorial > How to query superior and subordinate organizations in mysql

How to query superior and subordinate organizations in mysql

王林
Release: 2023-05-29 13:10:06
forward
1694 people have browsed it

Idea:

  • Customize mysql method

  • Use the two methods [FIND_IN_SET][group_concat] in mysql

(1) Prepare test data table

CREATE TABLE `org_test` (
  `org_no` varchar(32) NOT NULL COMMENT '机构编号',
  `org_name` varchar(200) NOT NULL COMMENT '机构名称',
  `p_org_no` varchar(32) DEFAULT NULL COMMENT '上级机构编号',
  PRIMARY KEY (`org_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy after login

Test data

INSERT INTO `org_test` VALUES ('1001', '福建省', null);
INSERT INTO `org_test` VALUES ('100101', '厦门市', '1001');
INSERT INTO `org_test` VALUES ('10010101', '思明区', '100101');
INSERT INTO `org_test` VALUES ('10010102', '湖里区', '100101');
INSERT INTO `org_test` VALUES ('10010103', '同安区', '100101');
INSERT INTO `org_test` VALUES ('100102', '福州市', '1001');
Copy after login

(2) Query all subordinate organizations of the designated organization (including itself)

delimiter $$
CREATE FUNCTION getOrgChild (orgNo varchar(32)) RETURNS varchar(1000) CHARSET utf8
BEGIN
	-- 定义临时变量
	DECLARE tmpOrg varchar(1000) DEFAULT '';
	-- 循环查询,orgNo不为空,则循环
	WHILE orgNo IS NOT NULL DO
		-- 拼接所有查询结果
		IF tmpOrg = '' THEN
			SET tmpOrg = CONCAT(tmpOrg, orgNo);
		ELSE
			SET tmpOrg = CONCAT(tmpOrg, ',', orgNo);
		END IF;
		-- 查询数据
		SELECT group_concat(org_no) INTO orgNo FROM org_test WHERE FIND_IN_SET(p_org_no, orgNo) > 0;
	END WHILE;
	
	-- 返回结果
	RETURN tmpOrg;
END $$
Copy after login

Test results:

How to query superior and subordinate organizations in mysql

(3) Query all parent organizations of the designated organization (including itself)

delimiter $$
CREATE FUNCTION getOrgParent (orgNo varchar(32)) RETURNS varchar(1000) CHARSET utf8
BEGIN
	-- 定义临时变量
	DECLARE tmpOrg varchar(1000) DEFAULT '';
	-- 循环查询,orgNo不为空,则循环
	WHILE orgNo IS NOT NULL DO
		-- 拼接所有查询结果
		IF tmpOrg = '' THEN
			SET tmpOrg = CONCAT(tmpOrg, orgNo);
		ELSE
			SET tmpOrg = CONCAT(tmpOrg, ',', orgNo);
		END IF;
		-- 查询数据
		SELECT group_concat(p_org_no) INTO orgNo FROM org_test WHERE FIND_IN_SET(org_no, orgNo) > 0;
	END WHILE;
	
	-- 返回结果
	RETURN tmpOrg;
END $$
Copy after login

Test results:

How to query superior and subordinate organizations in mysql

The above is the detailed content of How to query superior and subordinate organizations in mysql. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template