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

How to query superior and subordinate organizations in mysql

王林
王林forward
2023-05-29 13:10:061732browse

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;

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');

(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 $$

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 $$

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete