For a specified row, its parent node and its child nodes are determined by the CONNECT BY clause. The CONNECT BY clause must consist of two expressions compared with the equals (=) operator. One of these two expressions must be preceded by the keyword PRIOR.
To determine the child nodes of a specified row, perform the following steps:
- Evaluate parent_expr on the specified row.
- Evaluate child_expr on other rows resulting from the evaluation of table_expression.
- If parent_expr = child_expr, this row is a child node of the specified parent row.
- Repeat the process for all remaining rows in table_expression. All rows that satisfy the equation in step 3 are the child nodes of the specified parent row.
By repeating this process, you can regard each child node found in the preceding steps as a parent and build an inverted tree of nodes. The process is complete when the final set of child nodes has no child nodes. These nodes are the leaf nodes.
Examples
CREATE TABLE chinamap(id INT, parentid INT, name TEXT);
- Insert the data of Zhejiang Province.
INSERT INTO chinamap VALUES(1, NULL, 'Zhejiang');
- Insert the data of prefecture-level cities in Zhejiang Province.
INSERT INTO chinamap VALUES(101, 1, 'Hangzhou'); INSERT INTO chinamap VALUES(102, 1, 'Ningbo'); INSERT INTO chinamap VALUES(103, 1, 'Wenzhou'); INSERT INTO chinamap VALUES(104, 1, 'Jiaxing'); INSERT INTO chinamap VALUES(105, 1, 'Huzhou'); INSERT INTO chinamap VALUES(106, 1, 'Shaoxing'); INSERT INTO chinamap VALUES(107, 1, 'Jinhua'); INSERT INTO chinamap VALUES(108, 1, 'Quzhou'); INSERT INTO chinamap VALUES(109, 1, 'Zhoushan'); INSERT INTO chinamap VALUES(110, 1, 'Taizhou'); INSERT INTO chinamap VALUES(111, 1, 'Lishui');
- Insert the data of Hangzhou districts.
INSERT INTO chinamap VALUES(10101, 101, 'Shangcheng'); INSERT INTO chinamap VALUES(10102, 101, 'Xiacheng'); INSERT INTO chinamap VALUES(10103, 101, 'Xihu'); INSERT INTO chinamap VALUES(10104, 101, 'Gongshu'); INSERT INTO chinamap VALUES(10105, 101, 'Yuhang'); INSERT INTO chinamap VALUES(10106, 101, 'Binjiang'); INSERT INTO chinamap VALUES(10107, 101, 'Jianggan'); INSERT INTO chinamap VALUES(10108, 101, 'Xiaoshan');
select * from chinamap start with id = 1 connect by parentid = prior id;
A similar output is displayed: id | parentid | name
-------+----------+--------
1 | | Zhejiang
101 | 1 | Hangzhou
10101 | 101 | Shangcheng
10102 | 101 | Xiacheng
10103 | 101 | Xihu
10104 | 101 | Gongshu
10105 | 101 | Yuhang
10106 | 101 | Binjiang
10107 | 101 | Jianggan
10108 | 101 | Xiaoshan
102 | 1 | Ningbo
103 | 1 | Wenzhou
104 | 1 | Jiaxing
105 | 1 | Huzhou
106 | 1 | Shaoxing
107 | 1 | Jinhua
108 | 1 | Quzhou
109 | 1 | Zhoushan
110 | 1 | Taizhou
111 | 1 | Lishui
(20 rows)