* 階層構造 [#m7b5f032]
* 2階層構造のテーブルで親を求める [#m7b5f032]
** 前提 [#y809d315]
階層構造を表すテーブルtblを考える。
*** スキーマ [#k498eaac]
- id PK
- p_id 親ID(parent id)
- name IDの名前
*** データ [#r280852f]
id | p_id | name
----+------+------
1 | 1 | A
2 | 2 | B
10 | 1 | A1
11 | 1 | A2
12 | 1 | A3
13 | 2 | B1
14 | 2 | B2
CREATE TABLE tbl (id int, p_id int, name text) ;
INSERT INTO tbl VALUES ( 1,1,'A' ), ( 2,2,'B' );
INSERT INTO tbl VALUES ( 10,1,'A1' ) , ( 11,1,'A2' ) , ( 12,1,'A3' );
INSERT INTO tbl VALUES ( 13,2,'B1' ), ( 14,2,'B2' );
** 親IDの名前を求める [#r089f038]
SELECT t1.id, t1.p_id, t1.name, t2.name FROM tbl t1 JOIN tbl t2 ON t1.p_id = t2.id ORDER BY t1.id;
id | p_id | name | name
----+------+------+------
1 | 1 | A | A
2 | 2 | B | B
10 | 1 | A1 | A
11 | 1 | A2 | A
12 | 1 | A3 | A
13 | 2 | B1 | B
14 | 2 | B2 | B