目录
一、环境
二、准备数据
三、根据父节点ID获取所有子节点
四、根据子节点获取所有的父节点
数据库:PostgreSQL
/* Navicat PGSQL Data Transfer Source Server : localhost_postgresql Source Server Version : 90617 Source Host : localhost:5432 Source Database : odc_test Source Schema : public Target Server Type : PGSQL Target Server Version : 90617 File Encoding : 65001 Date: 2021-04-30 22:22:15 */ -- ---------------------------- -- Table structure for sys_area -- ---------------------------- DROP TABLE IF EXISTS "public"."sys_area"; CREATE TABLE "public"."sys_area" ( "id" int8 NOT NULL, "name" varchar(100) COLLATE "default" NOT NULL, "parent_id" int8 ) WITH (OIDS=FALSE) ; -- ---------------------------- -- Records of sys_area -- ---------------------------- INSERT INTO "public"."sys_area" VALUES ('1', '重庆市', null); INSERT INTO "public"."sys_area" VALUES ('2', '渝中区', '1'); INSERT INTO "public"."sys_area" VALUES ('3', '九龙坡区', '1'); INSERT INTO "public"."sys_area" VALUES ('4', '开州区', '1'); INSERT INTO "public"."sys_area" VALUES ('5', '渝北区', '1'); INSERT INTO "public"."sys_area" VALUES ('6', '两江新区', '1'); INSERT INTO "public"."sys_area" VALUES ('7', '石桥铺街道', '3'); INSERT INTO "public"."sys_area" VALUES ('8', '二郎街道', '3'); INSERT INTO "public"."sys_area" VALUES ('9', '大进镇', '4'); -- ---------------------------- -- Alter Sequences Owned By -- ---------------------------- -- ---------------------------- -- Primary Key structure for table sys_area -- ---------------------------- ALTER TABLE "public"."sys_area" ADD PRIMARY KEY ("id");
WITH RECURSIVE cte AS ( SELECT n. ID, n. NAME, n.parent_id AS pid FROM sys_area AS n WHERE n. ID = 1 UNION ALL SELECT r. ID, r. NAME, cte. ID AS pid FROM cte JOIN sys_area AS r ON r.parent_id = cte. ID ) SELECT * FROM cte
结果信息:
WITH RECURSIVE cte AS ( SELECT n. ID, n. NAME, n.parent_id AS pid FROM sys_area AS n WHERE n. NAME LIKE '%二郎%' UNION ALL SELECT r. ID, r. NAME, r.parent_id AS pid FROM cte JOIN sys_area AS r ON cte.pid = r. ID ) SELECT * FROM cte
结果信息: