学向勤中得,萤窗万卷书。这篇文章主要讲述PostgreSQL递归查询相关的知识,希望能为你提供帮助。
1. 语法结构
with recursive 名字 as (
A.初始条件语句(非递归部分)
union [all]
B.递归部分语句
) [SELECT | INSERT | UPDATE | DELETE]
1.1 说明
- 前半部分A为初始条件语句,后半部分B为要进行的递归语句
- 先执行A语句,然后将A语句的结果作为B语句的条件,如果需要对查询结果去重则使用union进行连接,否则使用union all进行连接
2.1 表结构
DROP TABLE IF EXISTS "test"."rbac_menu";
CREATE TABLE "test"."rbac_menu" (
"id" int8 NOT NULL,
"pid" int8,
"menu_name" varchar(255) COLLATE "pg_catalog"."default"
)
;
COMMENT ON COLUMN "test"."rbac_menu"."id" IS ID;
COMMENT ON COLUMN "test"."rbac_menu"."pid" IS 父ID;
COMMENT ON COLUMN "test"."rbac_menu"."menu_name" IS 菜单名称;
-- ----------------------------
-- Records of rbac_menu
-- ----------------------------
INSERT INTO "test"."rbac_menu" VALUES (100101, 1001, 权限管理);
INSERT INTO "test"."rbac_menu" VALUES (10010101, 100101, 菜单管理);
INSERT INTO "test"."rbac_menu" VALUES (10010102, 100101, 用户管理);
INSERT INTO "test"."rbac_menu" VALUES (10010103, 100101, 角色管理);
INSERT INTO "test"."rbac_menu" VALUES (1001010101, 10010101, 设置角色);
INSERT INTO "test"."rbac_menu" VALUES (1001010102, 10010101, 设置用户);
INSERT INTO "test"."rbac_menu" VALUES (1001010301, 10010103, 查看);
INSERT INTO "test"."rbac_menu" VALUES (1001010302, 10010103, 新增);
INSERT INTO "test"."rbac_menu" VALUES (1001010303, 10010103, 修改);
INSERT INTO "test"."rbac_menu" VALUES (1001010304, 10010103, 删除);
-- ----------------------------
-- Primary Key structure for table rbac_menu
-- ----------------------------
ALTER TABLE "test"."rbac_menu" ADD CONSTRAINT "rbac_menu_pkey" PRIMARY KEY ("id");
2.1 根据父节点获取所有子节点信息
with recursive temp_table as (
select "id", pid, "menu_name" from rbac_menu where pid = 1001
union
select a."id", a.pid, a."menu_name" from rbac_menu a,temp_table b where a.pid = b."id"
) select * from temp_table
order by pid, "id";
2.2 根据子节点获取所有父节点信息
with recursive temp_table as (
select "id", pid, "menu_name" from rbac_menu where "id" = 10060101
union
select a."id", a.pid, a."menu_name" from rbac_menu a,temp_table b where a.id = b.pid
) select * from temp_table
order by pid desc, "id" desc
【PostgreSQL递归查询】
推荐阅读
- Cygwin/MSYS2文件夹书签功能函数favorite-dirs,调用Windows资源管理器快速打开文件夹;
- select into 时有无strict关键字的区别
- Python实现七段数码管时钟(动态刷新版)
- 一张纸(5毫米)折叠多少次可以达到珠穆朗玛峰的高度(8848米)()
- 如何在cmd命令行下切换目录
- N62-1
- Android Studio实现QQ的注册登录和好友列表界面的跳转
- 企业内网如何搭建安全的Harbor服务((超详细))
- 番外篇客户端开发(Electron)无源码如何做汉化