postgres遞迴查詢

2021-06-19 02:05:06 字數 1179 閱讀 4649

1、開發中我們經常會遇到資料庫中的資料存在存在上小級的父子關係,如全國的省市資訊,或者乙個公司的部門資訊等。

如果我們在查詢的時候使用遞迴的方法直接將資料查詢出來就可以避免我們在程式中在進行遞迴過濾資料了,下面我們以全國的省市為例,首先我們定義一張表,表的定義如下:

然後我們在其中放一些資料,資料如下:

遞迴有向上遞迴與向下遞迴,首先我們向下遞迴,查詢河南省下面的所有記錄,查詢語句如下:

with recursive temptable as (

select * from t_provinces where pid = 2

union all

select t_provinces.* from t_provinces, temptable where t_provinces.parentid = temptable.pid

)select * from temptable order by pid;

查詢結果如圖:

這樣就將河南省下面的所有記錄全部查了出來。

然後我們向上遞迴,查詢欒川縣的所有父記錄。查詢語句如下:

with recursive temptable as (

select * from t_provinces where pid = 28

union all

select t_provinces.* from t_provinces, temptable where t_provinces.pid = temptable.parentid

)select * from temptable order by pid;

查詢結果圖如下:

這樣就查詢出來了欒川縣的所有父記錄。

Postgres 子查詢 介紹

postgres子查詢主要包含如下幾個關鍵字 exists,in,not in,any some,all,詳細介紹如下 exists subquery exists的引數是乙個任意的select語句,或者說子查詢。系統對子查詢進行運算以判斷它是否返回行。如果它至少返回一行,那麼exists的結果就為...

oracle 遞迴查詢 Oracle遞迴查詢

1.1 建立表與插入資料 create table district id number 10 not null,parent id number 10 name varchar2 255 byte not null alter table district add constraint distr...

mysql遞迴查詢統計 mysql遞迴查詢

樣例資料 create table treenodes id int primary key,nodename varchar 20 pid int select from treenodes id nodename pid 1 a 0 2 b 1 3 c 1 4 d 2 5 e 2 6 f 3 7...