두 개의 테이블이 있습니다. 하나는 sections
, 여기에는 id
, a parent_table
및 a parent_id
가 있고 다른 pages
하나에는 id
및 status
(및 기타) 열이 있습니다. 섹션의 상위는 parent_table
값 에 따라 다른 섹션 또는 페이지가 될 수 있습니다 . 주어진 섹션이 status = 1
페이지 에 있는지 여부를 창 기능을 사용하여 어떻게 알 수 있습니까? (MySQL 8.0 (또는 MariaDB 10.2)을 사용하지만 절실하게 필요한 경우 postgresql로 변환 할 수 있습니다).
예제 데이터 :
id|parent_table|parent_id
1 |pages |1
2 |sections |1
3 |pages |2
4 |sections |2
id|status
1|1
2|0
샘플 데이터를 다시 생성하려면 :
create table pages (id int not null primary key, status int not null) collate utf8mb4_general_ci;
create table sections (id int not null primary key, parent_table varchar(20), parent_id int not null) collate utf8mb4_general_ci;
insert into pages values (1,1),(2,0);
insert into sections values (1,'pages',1),(2,'sections',1),(3,'pages',2),(4,'sections',2);
모든 섹션에 해당하는 페이지 상태를 가져 오려면 다음 재귀 쿼리를 사용할 수 있습니다.
with recursive r as (
select s.id as section_id, s.parent_id, s.parent_table
from sections s
union all
select r.section_id, s.parent_id, s.parent_table
from r
join sections s on s.id = r.parent_id and r.parent_table = 'sections'
)
select r.section_id, p.id as page_id, p.status
from r
join pages p on p.id = r.parent_id
where r.parent_table = 'pages';
결과:
| section_id | page_id | status |
| ---------- | ------- | ------ |
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 4 | 1 | 1 |
| 3 | 2 | 0 |
재귀는 모든 섹션에서 루트 섹션으로 트리를 순회합니다. 이렇게하면 내부 쿼리의 단일 섹션으로 결과를 제한 할 수 있습니다. 예 : 섹션 3의 상태 만 알고 싶다면 RCTE의 첫 번째 UNION 부분에 WHERE 절을 사용합니다.
with recursive r as (
select s.id as section_id, s.parent_id, s.parent_table
from sections s
where s.id = 3 -- limit to a single section
union all
select r.section_id, s.parent_id, s.parent_table
from r
join sections s on s.id = r.parent_id and r.parent_table = 'sections'
)
select r.section_id, p.id as page_id, p.status
from r
join pages p on p.id = r.parent_id
where r.parent_table = 'pages';
결과:
| section_id | page_id | status |
| ---------- | ------- | ------ |
| 3 | 2 | 0 |
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다